Python調(diào)用系統(tǒng)命令os.system()和os.popen()的實(shí)現(xiàn)
作為一門(mén)腳本語(yǔ)言,寫(xiě)腳本時(shí)執(zhí)行系統(tǒng)命令可以說(shuō)很常見(jiàn)了,python提供了相關(guān)的模塊和方法。
os模塊提供了訪問(wèn)操作系統(tǒng)服務(wù)的功能,由于涉及到操作系統(tǒng),它包含的內(nèi)容比較多,這里只說(shuō)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()是在當(dāng)前進(jìn)程中打開(kāi)一個(gè)子shell(子進(jìn)程)來(lái)執(zhí)行系統(tǒng)命令。
官方說(shuō)法:
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.
這個(gè)方法只返回狀態(tài)碼,執(zhí)行結(jié)果會(huì)輸出到stdout,也就是輸出到終端。不過(guò)官方建議使用subprocess模塊來(lái)生成新進(jìn)程并獲取結(jié)果是更好的選擇。
>>> 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:要執(zhí)行的命令。
mode:打開(kāi)文件的模式,默認(rèn)為'r',用法與open()相同。
buffering:0意味著無(wú)緩沖;1意味著行緩沖;其它正值表示使用參數(shù)大小的緩沖。負(fù)的bufsize意味著使用系統(tǒng)的默認(rèn)值,一般來(lái)說(shuō),對(duì)于tty設(shè)備,它是行緩沖;對(duì)于其它文件,它是全緩沖。
官方說(shuō)法:
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;
這個(gè)方法會(huì)打開(kāi)一個(gè)管道,返回結(jié)果是一個(gè)連接管道的文件對(duì)象,該文件對(duì)象的操作方法同open(),可以從該文件對(duì)象中讀取返回結(jié)果。如果執(zhí)行成功,不會(huì)返回狀態(tài)碼,如果執(zhí)行失敗,則會(huì)將錯(cuò)誤信息輸出到stdout,并返回一個(gè)空字符串。這里官方也表示subprocess模塊已經(jīng)實(shí)現(xiàn)了更為強(qiáng)大的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'>
讀取執(zhí)行結(jié)果:
>>> 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']
這里使用os.popen來(lái)獲取設(shè)備號(hào),使用os.system來(lái)啟動(dòng)macaca服務(wù)(有時(shí)間了將macaca的一些經(jīng)歷寫(xiě)寫(xiě)吧)。
兩者的區(qū)別是:
(1)os.system(cmd)的返回值只會(huì)有0(成功),1,2
(2)os.popen(cmd)會(huì)把執(zhí)行的cmd的輸出作為值返回。
參考:
https://docs.python.org/3/library/os.html#os.system
https://docs.python.org/3/library/os.html#os.popen
到此這篇關(guān)于Python調(diào)用系統(tǒng)命令os.system()和os.popen()的實(shí)現(xiàn)的文章就介紹到這了,更多相關(guān)Python os.system()和os.popen()內(nèi)容請(qǐng)搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持腳本之家!
- python基礎(chǔ)教程之popen函數(shù)操作其它程序的輸入和輸出示例
- Python?subprocess.Popen?實(shí)時(shí)輸出?stdout的解決方法(正確管道寫(xiě)法)
- Python調(diào)用系統(tǒng)命令的四種方法詳解(os.system、os.popen、commands、subprocess)
- 解決python3中os.popen()出錯(cuò)的問(wèn)題
- python中的subprocess.Popen()使用詳解
- 對(duì)Python subprocess.Popen子進(jìn)程管道阻塞詳解
- Python中的Popen函數(shù)demo演示
相關(guān)文章
Python循環(huán)實(shí)現(xiàn)n的全排列功能
這篇文章主要介紹了Python循環(huán)實(shí)現(xiàn)n的全排列功能,本文給大家介紹的非常詳細(xì),具有一定的參考借鑒價(jià)值,需要的朋友可以參考下2019-09-09
解決pycharm py文件運(yùn)行后停止按鈕變成了灰色的問(wèn)題
今天小編就為大家分享一篇解決pycharm py文件運(yùn)行后停止按鈕變成了灰色的問(wèn)題,具有很好的參考價(jià)值,希望對(duì)大家有所幫助。一起跟隨小編過(guò)來(lái)看看吧2018-11-11
Python實(shí)現(xiàn)雙X軸雙Y軸繪圖的示例詳解
這篇文章主要介紹了如何利用fig.add_subplot和axes.twinx().twiny()方法實(shí)現(xiàn)雙X軸雙Y軸繪圖,文中的示例代碼講解詳細(xì),快跟隨小編一起動(dòng)手嘗試一下吧2022-04-04
Python編程pydantic觸發(fā)及訪問(wèn)錯(cuò)誤處理
這篇文章主要為大家介紹了Python編程中pydantic會(huì)觸發(fā)及發(fā)生訪問(wèn)錯(cuò)誤的處理,有需要的朋友可以借鑒參考下,希望能夠有所幫助,祝大家多多進(jìn)步2021-09-09
Python入門(mén)基礎(chǔ)之?dāng)?shù)字字符串與列表
這篇文章主要給大家介紹了關(guān)于Python入門(mén)基礎(chǔ)之?dāng)?shù)字字符串與列表的相關(guān)資料,文中通過(guò)示例代碼介紹的非常詳細(xì),對(duì)大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價(jià)值,需要的朋友們下面隨著小編來(lái)一起學(xué)習(xí)學(xué)習(xí)吧2021-02-02
python實(shí)現(xiàn)簡(jiǎn)單的TCP代理服務(wù)器
這篇文章主要介紹了python實(shí)現(xiàn)簡(jiǎn)單的TCP代理服務(wù)器,包含了完整的實(shí)現(xiàn)過(guò)程及對(duì)應(yīng)的源碼與說(shuō)明文檔下載,非常具有參考借鑒價(jià)值,需要的朋友可以參考下2014-10-10
Python+matplotlib實(shí)現(xiàn)繪制等高線圖示例詳解
在matplotlib.pyplot中除了可以繪制常規(guī)圖表如折線、柱狀、散點(diǎn)等,還可以繪制常用在地理上的平面展示地型的等高線圖,本文主要為大家介紹了如何利用matplotlib繪制等高線圖,需要的可以參考一下2021-12-12

