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:
song@ubuntu:~$ vi test.sh
song@ubuntu:~$ more test.sh
#!/bin/bash
echo 'hello python!'
echo 'hello world!'
exit 1
song@ubuntu:~$
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,用了以后,立竿見影!