溫馨提示×

您好,登錄后才能下訂單哦!

密碼登錄×
登錄注冊(cè)×
其他方式登錄
點(diǎn)擊 登錄注冊(cè) 即表示同意《億速云用戶(hù)服務(wù)條款》

subprocess模塊

發(fā)布時(shí)間:2020-07-28 14:36:59 來(lái)源:網(wǎng)絡(luò) 閱讀:616 作者:DevOperater 欄目:編程語(yǔ)言

1.subprocess模塊介紹

我們經(jīng)常需要通過(guò)Python去執(zhí)行一條系統(tǒng)命令或腳本,系統(tǒng)的shell命令是獨(dú)立于你的python進(jìn)程之外的,每執(zhí)行一條命令,就是發(fā)起一個(gè)新進(jìn)程,通過(guò)python調(diào)用系統(tǒng)命令或腳本的模塊在python2有os.system,,commands,popen2等也可以,比較亂,于是官方推出了subprocess,目地是提供統(tǒng)一的模塊來(lái)實(shí)現(xiàn)對(duì)系統(tǒng)命令或腳本的調(diào)用

"os.system獲取不到返回值"
>>> import os
>>> a = os.system("df -h") 
Filesystem      Size  Used Avail Use% Mounted on
/dev/sda3        98G  1.9G   97G   2% /
devtmpfs        479M     0  479M   0% /dev
tmpfs           489M     0  489M   0% /dev/shm
tmpfs           489M  6.7M  482M   2% /run
tmpfs           489M     0  489M   0% /sys/fs/cgroup
/dev/sda1      1014M  120M  895M  12% /boot
tmpfs            98M     0   98M   0% /run/user/0
>>> a
0
" os.popen可以獲取到返回值"
>>> os.popen("df -h")
<open file 'df -h', mode 'r' at 0x7f95dedd0780>
>>> f = os.popen("df -h")
>>> f.read()
'Filesystem      Size  Used Avail Use% Mounted on\n/dev/sda3        98G  1.9G   97G   2% /\ndevtmpfs        479M     0  479M   0% /dev\ntmpfs           489M     0  489M   0% /dev/shm\ntmpfs           489M  6.7M  482M   2% /run\ntmpfs           489M     0  489M   0% /sys/fs/cgroup\n/dev/sda1      1014M  120M  895M  12% /boot\ntmpfs            98M     0   98M   0% /run/user/0\n'

"python2中的commands模塊"
>>> import commands
>>> commands.getstatusoutput("df -h")
(0, 'Filesystem      Size  Used Avail Use% Mounted on\n/dev/sda3        98G  1.8G   97G   2% /\ndevtmpfs        479M     0  479M   0% /dev\ntmpfs           489M     0  489M   0% /dev/shm\ntmpfs           489M  6.7M  482M   2% /run\ntmpfs           489M     0  489M   0% /sys/fs/cgroup\n/dev/sda1      1014M  120M  895M  12% /boot\ntmpfs            98M     0   98M   0% /run/user/0')

2.subprocess執(zhí)行命令

2.1sbuprocess執(zhí)行命令的三種方法

subprocess.run(*popenargs, input=None, timeout=None, check=False, **kwargs) #官方推薦

subprocess.call(*popenargs, timeout=None, **kwargs) #跟上面實(shí)現(xiàn)的內(nèi)容差不多,另一種寫(xiě)法

subprocess.Popen() #上面各種方法的底層封裝
"subprocess.run"
>>> a = subprocess.run(["df","-h"])
Filesystem      Size  Used Avail Use% Mounted on
/dev/sda3        98G  2.3G   96G   3% /
devtmpfs        479M     0  479M   0% /dev
tmpfs           489M     0  489M   0% /dev/shm
tmpfs           489M  6.8M  482M   2% /run
tmpfs           489M     0  489M   0% /sys/fs/cgroup
/dev/sda1      1014M  120M  895M  12% /boot
tmpfs            98M     0   98M   0% /run/user/0
>>> a.args
['df', '-h']
>>> a.returncode
0
>>> a.check_returncode()

>>> a = subprocess.run(["df","-h"],stdout=subprocess.PIPE,stderr=subprocess.PIPE)
>>> a.stdout
b'Filesystem      Size  Used Avail Use% Mounted on\n/dev/sda3        98G  2.3G   96G   3% /\ndevtmpfs        479M     0  479M   0% /dev\ntmpfs           489M     0  489M   0% /dev/shm\ntmpfs           489M  6.8M  482M   2% /run\ntmpfs           489M     0  489M   0% /sys/fs/cgroup\n/dev/sda1      1014M  120M  895M  12% /boot\ntmpfs            98M     0   98M   0% /run/user/0\n'
>>> a.stderr
b''

>>> a = subprocess.run(["dsf","-h"],stdout=subprocess.PIPE,stderr=subprocess.PIPE)
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
  File "/usr/local/python3Dir/lib/python3.6/subprocess.py", line 403, in run
    with Popen(*popenargs, **kwargs) as process:
  File "/usr/local/python3Dir/lib/python3.6/subprocess.py", line 709, in __init__
    restore_signals, start_new_session)
  File "/usr/local/python3Dir/lib/python3.6/subprocess.py", line 1344, in _execute_child
    raise child_exception_type(errno_num, err_msg, err_filename)
FileNotFoundError: [Errno 2] No such file or directory: 'dsf': 'dsf'

>>> a = subprocess.run(["df","-h","|","grep","a"],stdout=subprocess.PIPE,stderr=subprocess.PIPE,shell=True)
>>> a.stdout      
b'Filesystem     1K-blocks    Used Available Use% Mounted on\n/dev/sda3      102709252 2337100 100372152   3% /\ndevtmpfs          490020       0    490020   0% /dev\ntmpfs             499848       0    499848   0% /dev/shm\ntmpfs             499848    6900    492948   2% /run\ntmpfs             499848       0    499848   0% /sys/fs/cgroup\n/dev/sda1        1038336  121872    916464  12% /boot\ntmpfs              99972       0     99972   0% /run/user/0\n'
"subprocess.call"
>>> a = subprocess.call(["df","-h"])
Filesystem      Size  Used Avail Use% Mounted on
/dev/sda3        98G  2.3G   96G   3% /
devtmpfs        479M     0  479M   0% /dev
tmpfs           489M     0  489M   0% /dev/shm
tmpfs           489M  6.8M  482M   2% /run
tmpfs           489M     0  489M   0% /sys/fs/cgroup
/dev/sda1      1014M  120M  895M  12% /boot
tmpfs            98M     0   98M   0% /run/user/0
>>> 
"subprocess.Popen會(huì)發(fā)起新的進(jìn)程,不影響主進(jìn)程"
>>> a = subprocess.Popen("sleep 10",stdout=subprocess.PIPE,stderr=subprocess.PIPE,shell=True)#10秒后返回
>>> a = subprocess.Popen("sleep 10",stdout=subprocess.PIPE,stderr=subprocess.PIPE,shell=True)#立刻返回,poll()可以用來(lái)監(jiān)控命令是否結(jié)束
>>> a.poll()
>>> a.poll()
>>> a.poll()
0
"運(yùn)行函數(shù)"
>>> def sayhi():
    print("hello")... 
... 
>>> sayhi()
hello
>>> a = subprocess.Popen("echo $PWD",stdout=subprocess.PIPE,stderr=subprocess.PIPE,shell=True,preexec_fn=sayhi)
>>> a.stdout.read()
b'hello\n/usr/local/python3/Python-3.6.3\n'
>>> 
>>> a = subprocess.Popen("echo $PWD",stdout=subprocess.PIPE,stderr=subprocess.PIPE,shell=True,cwd="/tmp",preexec_fn=sayhi)
>>> a.stdout.read()
b'hello\n/tmp\n'
>>> 
>>> a = subprocess.Popen("echo $PWD;sleep 15",stdout=subprocess.PIPE,stderr=subprocess.PIPE,shell=True,cwd="/tmp",preexec_fn=sayhi)
>>> a.wait() #等在這里直到上面的程序運(yùn)行完成
0
>>> 
"Popen程序的終止"
>>> a = subprocess.Popen("echo $PWD;sleep 100",stdout=subprocess.PIPE,stderr=subprocess.PIPE,shell=True)
>>> a.terminate()#程序的終止
>>> a.kill())#程序的終止
>>> 
>>> import signal
>>> a = subprocess.Popen("echo $PWD;sleep 100",stdout=subprocess.PIPE,stderr=subprocess.PIPE,shell=True)
>>> a.send_signal(signal.SIGKILL)
"communicate()程序交互,只能交互一次,再次交互會(huì)報(bào)錯(cuò)"
>>> import subprocess
>>> a = subprocess.Popen("python3 guessage.py",stdout=subprocess.PIPE,stderr=subprocess.PIPE,shell=True)
>>> a.communicate(b'33')

(b'input the age of you think:you should input one number!\ninput the age of you think:you should input one number!\ninput the age of you think:you should input one number!\n', b'')
>>> 
>>> a.communicate(b'12')
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
  File "/usr/local/python3Dir/lib/python3.6/subprocess.py", line 818, in communicate
    raise ValueError("Cannot send input after starting communication")
ValueError: Cannot send input after starting communication
>>> 
向AI問(wèn)一下細(xì)節(jié)

免責(zé)聲明:本站發(fā)布的內(nèi)容(圖片、視頻和文字)以原創(chuàng)、轉(zhuǎn)載和分享為主,文章觀點(diǎn)不代表本網(wǎng)站立場(chǎng),如果涉及侵權(quán)請(qǐng)聯(lián)系站長(zhǎng)郵箱:is@yisu.com進(jìn)行舉報(bào),并提供相關(guān)證據(jù),一經(jīng)查實(shí),將立刻刪除涉嫌侵權(quán)內(nèi)容。

AI