Which is better Unix and Python

Python course

Python and the Shell


Shell is a term that is used a lot and yet is often understood and misunderstood in different ways. As is easy to see, the name comes from English. Shell means shell and shell, such as the mussel shell. The function of a clam shell is primarily to protect the clam. The conch shell separates and protects the inside from the outside. The shell separates the core of the operating system from the shell user. The shell provides him or her with robust and easy-to-use functions so that he or she does not have to use the complicated and error-prone operating system functions.

In general, there are two types of shell for operating systems,
  • the command line (CLI)
  • the graphical user interfaces (GUI)
In most cases, however, the term is used as a synonym for command line interpreter (CLI), such as the Bourne shell, C shell or Bash under Unix.

System programming

System programming is the programming of software components that are part of the operating system or that have to communicate closely with the operating system or with the underlying hardware. System-related software, such as the sys module in Python, acts as an abstraction layer between the application, the Python program, and the operating system. With the help of this abstraction layer, applications can be implemented independently of the platform, even if they access operating system functionalities directly.

Python is particularly good for system programming. Everything that also applies to Python in general also distinguishes the advantages of Python in low-level programming:
  • Simple and clear
  • Good structurability
  • high flexibility

The os module

The os module is the most important module for interaction with the operating system and enables platform-independent programming through abstract methods. At the same time, it is also possible to use functions such as os.system () or the exec * () function family to incorporate operating system-dependent program parts. (We discussed the family of exec * () functions in the chapter "Forks and Forking in Python".)
The os module offers many different methods, such as accessing the file system.

Execute shell scripts with os.system ()

In Python it is difficult to read a character without pressing the return key. It's very easy to do in the bash shell. There is the read command. "" waits until a key is pressed. If you use os.system () in Python, you can very easily write a function getch () that also waits for a character in Python using read. import os def getch (): os.system ("bash -c \" read -n 1 \ "") getch () The above script only works under Linux. Under Windows you have to import the module msvcrt. Strictly speaking, the getch function from this module. Even if we are primarily concerned with Linux, here is the solution under Windows: from msvcrt import getch The following solution implements a getch () function depending on the operating system: import os, platform if platform.system () == " Windows ": import msvcrt def getch (): if platform.system () ==" Linux ": os.system (" bash -c \ "read -n 1 \" ") else: msvcrt.getch () print (" Press the key! ") Getch () print (" Okay ") The previous example has a problem. The getch () function in the previous example should actually return a value, i.e. the character that was read. However, os.system () does not return the evaluated value of the command string. os.system () is implemented as a call to the standard C function system (). The return value from os.system () is not specified by POSIX and is therefore system-dependent. In the following script we show how shell commands and shell scripts can be executed using os.popen () and how the results can be read into Python: >>> import os >>> dir = os.popen ("ls"). readlines () >>> print dir ['curses.py \ n', 'curses.pyc \ n', 'errors.txt \ n', 'getch.py ​​\ n', 'getch.pyc \ n', ' more.py \ n ',' numbers.txt \ n ',' output.txt \ n ',' redirecting_output.py \ n ',' redirecting_stderr2.py \ n ',' redirecting_stderr.py \ n ',' streams. py \ n ',' test.txt \ n '] >>> The shell output can also be read in line by line, as can be seen in the following script: import os command = "" while (command! = "exit") : command = raw_input ("Command:") handle = os.popen (command) line = "" while line: line = handle.read () print line handle.close () print "Ciao, that's it!"

subprocess module

Since Python 2.4. there is the subprocess module.
With subprocess it is possible to create new processes via spawn and to connect to their input / output / error channels in order to receive the return codes.
The subprocess module is intended to replace other modules:
  • os.system
  • os.spawn *
  • os.popen *
  • popen2. *
  • commands. *

Working with subprocess

Instead of the system command of the os module
os.system ('touch xyz') you formulate the following instructions in the subprocess module to get the results of the script: >>> import subprocess >>> x = subprocess.Popen (['touch', 'xyz'] ) >>> print x >>> x.poll () 0 >>> x.returncode 0 The command can be sent under Python with the subprocess module as follows: p = subprocess.Popen ( ['cp', '- r', "xyz", "abc"]) Spaces and shell metacharacters ($,> etc.) do not have to be "escaped". If you want to emulate the behavior of os.system, set shell = True and enter a string instead of a list: p = subprocess.Popen ("cp -r xyz abc", shell = True)
If you want to use the output of a shell script in Python, you have to set stdout to subprocess.PIPE: >>> process = subprocess.Popen (['ls', '- l'], stdout = subprocess.PIPE) >> > print process.stdout.read () total 132 -rw-r - r-- 1 bernd bernd 0 2010-10-06 10:03 abc -rw-r - r-- 1 bernd bernd 0 2010-10- 06 10:04 abcd -rw-r - r-- 1 bernd bernd 660 2010-09-30 21:34 curses.py

It can make sense to wait after starting a subprocess with .wait () until the started script has been completely executed: >>> process = subprocess.Popen (['ls', '- l'], stdout = subprocess.PIPE ) >>> process.wait () 0

Functions for editing directories and files

chdir (path)The current working directory is changed to path.
getcwd ()Returns a string with the current working directory.
getcwdu ()like getcwd () only unicode as output
listdir (path)A list of the contents (filenames, subdirectories, etc.) of the path directory
mkdir (path [, mode = 0755])A new directory is created. If higher-level directories do not exist in path, an error is generated and no directory is created.
makedirs (name [, mode = 511])Like mkdir, but also creates higher-level directories automatically.
rename (old, new)A file or directory is being renamed
renames (old, new)Like rename, but also higher-level directories in "old" are created if they do not exist. However, only if you have the necessary authorization.
rmdir (path)A directory is deleted if it is empty.

The shutil module provides additional functions that work on files and directories. Among other things, it offers options for copying files and directories, e.g. shutil.copyfile (src, dst).