Python Memo: Let’s get started Python

This was a mystery statement for me.

if __name__ ==”__main__”:

This seems

start position of module executed case…

Found clearer explanation from Learning Python, oreilly.

This statement check that the program file (module) is whether executed as a program or imported as module, and if it is as a program, do some statements in the if statement scope.

__name__ is a builtin attribute.

It’s like a bash or perl.

Useful variables which have attribute.

__init__.py

this module is necessary for each directories which used as package.

Daily memo 190129 Tue

First of all, forgot to go to TSUTAYA at 28th day when has number 8. The days have number 8 are 50% off cd rental…

I planned to rent Lion King OST, Hakuna Matata this is it.

Today cleaned my room, put books to a 📦 , read books around.

Unix philosophy, The weblog handbook, Dive into python…

Ai, leverage, web links collection

A primer on scientific programming with python

I read. It’s recently fashionable style way of writing tempo, and intriguing that it’s essential mathematical programming.

The academic hackers style😅

My name is Masa -> mather

Not mother 😂

So will write about math.

I’m planning start from facilitating my “Plotting program in Java and swing”. Because this includes a lot of important math elements. It’s think like a numerical world creatures…

Or something like secrets of arithmetics 😏

Programming column: A programming unified viewand

My case fun of programming started from bash script. Was really wanted to accustomed with unix or Linux culture bought tons of unix used books mainly under $10.. lol.

Before that I learned Java but it’s hard to living well with OS ( computing environment). Especially make files, directories, reading, writing, using regular expression and co-operating with environment.

Bash is perfect for co-work with the environments. But not Object Oriented so hard to code maintain and manage.

Once you got through one bash book ( My case O’reilly’s “Learning bash shell” Second edition maybe) u will be interested in Sed & Awk.

Sed is “Stream EDitor” by my memory. This using ed text editor inside might be? Ed is very old text editing program. AT&T Bell Lab’s product. Line orient and matrix(mother) of Vi text editor. It won’t even display whole text. 🤓 Because it’s for printer type display(teletype). In the era no crt display and printed to papers. So this was efficient for paper printer.

Awk is acronym for “Adrian will kome “. 🤕

This is splendid language, Jon Bentley was attracted . Perl’s main influencer..

Python is made by masters of low or middle level languages. There are tons of splendid libraries, functions and programming style guide lines.

The point of the view rom function builder on Java, python or frameworks like angular are built arts by the hackers.

Now they must be loving Arduino or Raspy because that’s EECS “Ying and Yang”.

Compiler knowledge is essential.

 

Almost Unix commands are written in C.
But those are very small programs. Like things between programs and API.
Programming approach history is getting generality as it in mathematical description.
Unix commands are more like organic, C? Lol.
I thought like this when reviewing Grep command usage and bash programming.

To be continued,,,

Import youtube-dl package in Python

*package -> A module that contains other modules. Like directory to the files.
*module -> A file that contains a collection of related  functions and other definitions. Maybe like class file in Java. One unit of programs.

One resolution is add path to module search path.

This thread seems helpful.
https://stackoverflow.com/questions/33893610/correct-way-of-absolute-import-in-python-2-7
#from #import #singleton #virtualenv #builtin-modules #module_object #

@ThinkPython @Python Language Reference Manual @Python in a nutshell

>>> import sys
>>> print sys.path
[”, ‘/usr/local/lib/python2.7/dist-packages/pip-9.0.1-py2.7.egg’, ‘/usr/lib/python2.7’, ‘/usr/lib/python2.7/plat-x86_64-linux-gnu’, ‘/usr/lib/python2.7/lib-tk’, ‘/usr/lib/python2.7/lib-old’, ‘/usr/lib/python2.7/lib-dynload’, ‘/usr/local/lib/python2.7/dist-packages’, ‘/usr/lib/python2.7/dist-packages’, ‘/usr/lib/python2.7/dist-packages/PILcompat’, ‘/usr/lib/python2.7/dist-packages/gtk-2.0’, ‘/usr/lib/python2.7/dist-packages/wx-3.0-gtk2’]

Starting Python. Memo for migration from bash, java.

“Comment out.  => #

#logical line #physical line

 

“Get length of an array => use len() (built-in) , __len__() (special method) methods

len(container)  — Built-in Functions, Core Built-ins

print len(list_name)

#container #special method #PyObject

“Make list

list_name = [‘first’, ‘python’, ‘bow-wow’]

 

“static import declaration in python?

call function without package name

ex

>> import subprocess
>>> check_output([“ls”])  ERROR

>> subprocess.check_output([“ls”]) ok

I was reading /home/masa/jython2.7.0/Lib/subprocess.py which is source code of subprocess in jython. This was very clear. And example statement was

 >>> check_output(["ls", "-l", "/dev/null"])
 'crw-rw-rw- 1 root root 1, 3 Oct 18 2007 /dev/null\n'
def check_output(*popenargs, **kwargs):
 r"""Run command with arguments and return its output as a byte string.

If the exit code was non-zero it raises a CalledProcessError. The
 CalledProcessError object will have the return code in the returncode
 attribute and output in the output attribute.

The arguments are the same as for the Popen constructor. Example:

>>> check_output(["ls", "-l", "/dev/null"])
 'crw-rw-rw- 1 root root 1, 3 Oct 18 2007 /dev/null\n'

 

 

Creating background processes in python.

I’m researching how to make background process in python like “command &” in bash.

KEYWORD #OSMODULE #IPC #Inter-Process Communication

“use subprocess module

“use os.spawn os.popen or os.system ( os module)

#THREADS AND PROCESSES #Running other programs

system fuction

this is easy, but can’t control the external program.

import os
os.system("command plus option include &") #formally os.system(cmd)

ex

#!/usr/bin/env python
import os
os.system("ls -l ")

this output result of “ls -l” to the console.

And os.system(“ls -l & “) is same result.

 

spawn function

import os
os.spawnl(os.P_DETACH, 'some_long_running_command')

 

os.fork , os.exec

try:
    pid = os.fork()
except OSError, e:
    ## some debug output
    sys.exit(1)
if pid == 0:
    ## eventually use os.putenv(..) to set environment variables
    ## os.execv strips of args[0] for the arguments
    os.execv(args[0], args)

Example code from https://code.i-harness.com/ja/q/12402a

#popen #

exec => unix like platform (because of using fork command)

spawn, popen => cross platform

spawn|run commands

spawn — to make a series of things happen or start to exist. 生む、引き起こす、卵、結果

spawn

https://docs.python.org/2/library/subprocess.html

this site recommends use subprocess or popen.

subprocess replace os.{system, spawn, popen, popen2, commands}

subprocess.call(args, *, stdin=None, stdout=None, stderr=None, shell=False)

subprocess.check_output(args, *, stdin=None, stderr=None, shell=False, universal_newlines=False)

 

popen|run programs

I’ve got error message.

:!./newLoop.py a b c
4
./newLoop.py
Usage: youtube-dl [OPTIONS] URL [URL...]

youtube-dl: error: You must provide at least one URL.
Type youtube-dl --help to see a list of all options.
Traceback (most recent call last):
 File "./newLoop.py", line 11, in <module>
 output=subprocess.check_output(["youtube-dl"])
 File "/usr/lib/python2.7/subprocess.py", line 574, in check_output
 raise CalledProcessError(retcode, cmd, output=output)
subprocess.CalledProcessError: Command '['youtube-dl']' returned non-zero exit status 2

shell returned 1

What is option “shell=True,False” means?

https://stackoverflow.com/questions/3172470/actual-meaning-of-shell-true-in-subprocess

use variable as command. Example. cmd = ls -l