1. 程式人生 > >python os.system()和os.popen()

python os.system()和os.popen()

1》python呼叫Shell指令碼,有兩種方法:os.system()和os.popen(),
前者返回值是指令碼的退出狀態碼,後者的返回值是指令碼執行過程中的輸出內容。
>>>help(os.system)
Help on built-in function system in module posix:
system(...)
    system(command) -> exit_status
    Execute the command (a string) in a subshell.

>>> help(os.popen)
Help on built-in function popen in module posix:
popen(...)
    popen(command [, mode='r' [, bufsize]]) -> pipe
    Open a pipe to/from a command returning a file object.

2》假定有一個shell指令碼test.sh:
[email protected]
:~$ vi test.sh
[email protected]:~$ more test.sh
#!/bin/bash
echo 'hello python!'
echo 'hello world!'
exit 1
[email protected]:~$ 
2.1》os.system(command):該方法在呼叫完shell指令碼後,返回一個16位的二進位制數,
低位為殺死所呼叫指令碼的訊號號碼,高位為指令碼的退出狀態碼
即指令碼中“exit 1”的程式碼執行後,os.system函式返回值的高位數則是1,如果低位數是0的情況下,
則函式的返回值是0x0100,換算為十進位制得到256。
要獲得os.system的正確返回值,可以使用位移運算(將返回值右移8位)還原返回值

>>> import os
>>> os.system("./test.sh")
hello python!
hello world!
256
>>> n=os.system("./test.sh")
hello python!
hello world!
>>> n
256
>>> n>>8
1
>>> 
2.2》os.popen(command):這種呼叫方式是通過管道的方式來實現,函式返回一個file物件
裡面的內容是指令碼輸出的內容(可簡單理解為echo輸出的內容),使用os.popen呼叫test.sh的情況:
>> import os
>>> os.popen("./test.sh")
<open file './test.sh', mode 'r' at 0x7f6cbbbee4b0>
>>> f=os.popen("./test.sh")
>>> f
<open file './test.sh', mode 'r' at 0x7f6cbbbee540>
>>> f.readlines()
['hello python!\n', 'hello world!\n']
>>> 
3》像呼叫”ls”這樣的shell命令,應該使用popen的方法來獲得內容,對比如下:
>>> import os
>>> os.system("ls")   #直接看到執行結果

Desktop    Downloads    Music     Public     Templates  Videos
Documents  examples.desktop  Pictures  systemExit.py  test.sh
0    #返回值為0,表示命令執行成功
>>> n=os.system('ls')
Desktop    Downloads    Music     Public     Templates  Videos
Documents  examples.desktop  Pictures  systemExit.py  test.sh
>>> n
0
>>> n>>8   #將返回值右移8位,得到正確的返回值
0
>>> f=os.popen('ls') #返回一個file物件,可以對這個檔案物件進行相關的操作
>>> f
<open file 'ls', mode 'r' at 0x7f5303d124b0>
>>> f.readlines()
['Desktop\n', 'Documents\n', 'Downloads\n', 'examples.desktop\n', 'Music\n', 'Pictures\n', 'Public\n', 'systemExit.py\n', 'Templates\n', 'test.sh\n', 'Videos\n']
>>> 
總結:os.popen()可以實現一個“管道”,從這個命令獲取的值可以繼續被使用。因為它返回一個檔案物件,可以對這個檔案物件進行相關的操作。

但是如果要直接看到執行結果的話,那就應該使用os.system,用了以後,立竿見影!

友情連結: