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

來源:互聯網
上載者:User

標籤:from   str   stat   test   pip   sub   二進位   換算   load   

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,用了以後,立竿見影!

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

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.