天天看點

調用系統指令:os.system& os.popen

作為一門腳本語言,寫腳本時執行系統指令可以說很常見了,python提供了相關的子產品和方法。

os子產品提供了通路作業系統服務的功能,由于涉及到作業系統,它包含的内容比較多,這裡隻說system和popen方法。

>>> import os
>>> dir(os)
['DirEntry', 'F_OK', 'MutableMapping', 'O_APPEND', 'O_BINARY', 'O_CREAT', 'O_EXCL', 'O_NOINHERIT', 'O_RANDOM', 'O_RDONLY', 'O_RDWR', 'O_SEQUENTIAL', 'O_SHORT_LIVED', 'O_TEMPORARY', 'O_TEXT', 'O_TRUNC', 'O_WRONLY', 'P_DETACH', 'P_NOWAIT', 'P_NOWAITO', 'P_OVERLAY', 'P_WAIT', 'PathLike', 'R_OK', 'SEEK_CUR', 'SEEK_END', 'SEEK_SET', 'TMP_MAX', 'W_OK', 'X_OK', '_Environ', '__all__', '__builtins__', '__cached__', '__doc__', '__file__', '__loader__', '__name__', '__package__', '__spec__', '_execvpe', '_exists', '_exit', '_fspath', '_get_exports_list', '_putenv', '_unsetenv', '_wrap_close', 'abc', 'abort', 'access', 'altsep', 'chdir', 'chmod', 'close', 'closerange', 'cpu_count', 'curdir', 'defpath', 'device_encoding', 'devnull', 'dup', 'dup2', 'environ', 'errno', 'error', 'execl', 'execle', 'execlp', 'execlpe', 'execv', 'execve', 'execvp', 'execvpe', 'extsep', 'fdopen', 'fsdecode', 'fsencode', 'fspath', 'fstat', 'fsync', 'ftruncate', 'get_exec_path', 'get_handle_inheritable', 'get_inheritable', 'get_terminal_size', 'getcwd', 'getcwdb', 'getenv', 'getlogin', 'getpid', 'getppid', 'isatty', 'kill', 'linesep', 'link', 'listdir', 'lseek', 'lstat', 'makedirs', 'mkdir', 'name', 'open', 'pardir', 'path', 'pathsep', 'pipe', 'popen', 'putenv', 'read', 'readlink', 'remove', 'removedirs', 'rename', 'renames', 'replace', 'rmdir', 'scandir', 'sep', 'set_handle_inheritable', 'set_inheritable', 'spawnl', 'spawnle', 'spawnv', 'spawnve', 'st', 'startfile', 'stat', 'stat_float_times', 'stat_result', 'statvfs_result', 'strerror', 'supports_bytes_environ', 'supports_dir_fd', 'supports_effective_ids', 'supports_fd', 'supports_follow_symlinks', 'symlink', 'sys', 'system', 'terminal_size', 'times', 'times_result', 'truncate', 'umask', 'uname_result', 'unlink', 'urandom', 'utime', 'waitpid', 'walk', 'write']
           

os.system()

>>> help(os.system)
Help on built-in function system in module nt:

system(command)
    Execute the command in a subshell.
           

從字面意思上看,os.system()是在目前程序中打開一個子shell(子程序)來執行系統指令。

官方說法:

On Unix, the return value is the exit status of the process encoded in the format specified for wait().

The subprocess module provides more powerful facilities for spawning new processes and retrieving their results; using that module is preferable to using this function.
           

這個方法隻傳回狀态碼,執行結果會輸出到stdout,也就是輸出到終端。不過官方建議使用subprocess子產品來生成新程序并擷取結果是更好的選擇。

>>> os.system('ls')
access.log  douban.py  mail.py  myapp.py  polipo  proxychains  __pycache__   spider.py  test.py  users.txt
0
           

os.popen()

>>> help(os.popen)
Help on function popen in module os:

popen(cmd, mode='r', buffering=-1)
    # Supply os.popen()
           

cmd:要執行的指令。

mode:打開檔案的模式,預設為'r',用法與open()相同。

buffering:0意味着無緩沖;1意味着行緩沖;其它正值表示使用參數大小的緩沖。負的bufsize意味着使用系統的預設值,一般來說,對于tty裝置,它是行緩沖;對于其它檔案,它是全緩沖。

官方說法:

Open a pipe to or from command cmd. The return value is an open file object connected to the pipe, which can be read or written depending on whether mode is 'r' (default) or 'w'. 

The close method returns None if the subprocess exited successfully, or the subprocess’s return code if there was an error. 

This is implemented using subprocess.Popen;
           

這個方法會打開一個管道,傳回結果是一個連接配接管道的檔案對象,該檔案對象的操作方法同open(),可以從該檔案對象中讀取傳回結果。如果執行成功,不會傳回狀态碼,如果執行失敗,則會将錯誤資訊輸出到stdout,并傳回一個空字元串。這裡官方也表示subprocess子產品已經實作了更為強大的subprocess.Popen()方法。

>>> os.popen('ls')
<os._wrap_close object at 0x7f93c5a2d780>
>>> os.popen('la')
<os._wrap_close object at 0x7f93c5a37588>
>>> /bin/sh: la: command not found

>>> f = os.popen('ls')
>>> type(f)
<class 'os._wrap_close'>
           

讀取執行結果:

>>> f.readlines()
['access.log\n',  'douban.py\n', 'import_test.py\n', 'mail.py\n', 'myapp.py\n', 'polipo\n', 'proxychains\n', '__pycache__\n', 'spider.py\n', 'test.py\n', 'users.txt\n']