python環境下,執行系統命令方法

方法1:os.system
>>>import os
>>>os.system('ls')
anaconda-ks.cfg  Django-1.2.7  install.log.syslog  ptyprocess-0.5.1    server1.py    公共的    文檔
a.py         docker        mysite           pycharm-2016.3.2    server.py    模板    下載
client1.py     docker-1.7.1  paramiko-2.1.1       pycharm-license.txt    setuptools-2.0    視頻    音樂
client.py     install.log   pexpect-4.2.1       pycrypto-2.6.1    spawn-0.1    圖片    桌面
0
>>>
方法2:os.popen
>>>import os
>>>tmp = os.popen('ls')
>>>tmp.readlines()
anaconda-ks.cfg  Django-1.2.7  install.log.syslog  ptyprocess-0.5.1    server1.py    公共的    文檔
a.py         docker        mysite           pycharm-2016.3.2    server.py    模板    下載
client1.py     docker-1.7.1  paramiko-2.1.1       pycharm-license.txt    setuptools-2.0    視頻    音樂
client.py     install.log   pexpect-4.2.1       pycrypto-2.6.1    spawn-0.1    圖片    桌面
0
>>>
方法3:subprocess
>>> import subprocess
>>> subprocess.call(('ls'),shell=True)
anaconda-ks.cfg  Django-1.2.7  install.log.syslog  ptyprocess-0.5.1    server1.py    公共的    文檔
a.py         docker        mysite           pycharm-2016.3.2    server.py    模板    下載
client1.py     docker-1.7.1  paramiko-2.1.1       pycharm-license.txt    setuptools-2.0    視頻    音樂
client.py     install.log   pexpect-4.2.1       pycrypto-2.6.1    spawn-0.1    圖片    桌面
0
>>>

>>>p = subprocess.Popen('ls',shell=True,stdout=subprocess.PIPE,stderr=subprocess.STDOUT)
>>>p.stdout.readlines():
['anaconda-ks.cfg\n', 'a.py\n', 'client1.py\n', 'client.py\n', 'Django-1.2.7\n', 'docker\n', 'docker-1.7.1\n', 'install.log\n', 'install.log.syslog\n', 'mysite\n', 'paramiko-2.1.1\n', 'pexpect-4.2.1\n', 'ptyprocess-0.5.1\n', 'pycharm-2016.3.2\n', 'pycharm-license.txt\n', 'pycrypto-2.6.1\n', 'server1.py\n', 'server.py\n', 'setuptools-2.0\n', 'spawn-0.1\n', '\xe5\x85\xac\xe5\x85\xb1\xe7\x9a\x84\n', '\xe6\xa8\xa1\xe6\x9d\xbf\n', '\xe8\xa7\x86\xe9\xa2\x91\n', '\xe5\x9b\xbe\xe7\x89\x87\n', '\xe6\x96\x87\xe6\xa1\xa3\n', '\xe4\xb8\x8b\xe8\xbd\xbd\n', '\xe9\x9f\xb3\xe4\xb9\x90\n', '\xe6\xa1\x8c\xe9\x9d\xa2\n']
方法4:commands
>>>import commands
>>>commands.getoutput('date')
>>>'2017\xe5\xb9\xb4 05\xe6\x9c\x88 08\xe6\x97\xa5 \xe6\x98\x9f\xe6\x9c\x9f\xe4\xb8\x80 18:26:25 CST'
>>>commands.getstatusoutput('date')
>>>(0, '2017\xe5\xb9\xb4 05\xe6\x9c\x88 08\xe6\x97\xa5 \xe6\x98\x9f\xe6\x9c\x9f\xe4\xb8\x80 18:27:24 CST')


發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章