python subprocess模組

來源:互聯網
上載者:User

標籤:lsp   res   arguments   chain   fun   evel   this   signature   traceback   

Subprocess模組 

The subprocess module allows you to spawn new processes, connect to their input/output/error pipes, and obtain their return codes. This module intends to replace several older modules and functions:

os.systemos.spawn*

The recommended approach to invoking subprocesses is to use the run() function for all use cases it can handle. For more advanced use cases, the underlying Popen interface can be used directly.

The run() function was added in Python 3.5; if you need to retain compatibility with older versions, see the Older high-level API section.

subprocess.run(args, *, stdin=None, input=None, stdout=None, stderr=None, shell=False, timeout=None, check=False)

Run the command described by args. Wait for command to complete, then return a CompletedProcess instance.

The arguments shown above are merely the most common ones, described below in Frequently Used Arguments (hence the use of keyword-only notation in the abbreviated signature). The full function signature is largely the same as that of the Popen constructor - apart from timeout, input and check, all the arguments to this function are passed through to that interface.

This does not capture stdout or stderr by default. To do so, pass PIPE for the stdout and/or stderr arguments.

The timeout argument is passed to Popen.communicate(). If the timeout expires, the child process will be killed and waited for. The TimeoutExpired exception will be re-raised after the child process has terminated.

The input argument is passed to Popen.communicate() and thus to the subprocess’s stdin. If used it must be a byte sequence, or a string if universal_newlines=True. When used, the internal Popen object is automatically created withstdin=PIPE, and the stdin argument may not be used as well.

If check is True, and the process exits with a non-zero exit code, a CalledProcessError exception will be raised. Attributes of that exception hold the arguments, the exit code, and stdout and stderr if they were captured.

常用subprocess方法樣本

#執行命令,返回命令執行狀態 , 0 or 非0
>>> retcode = subprocess.call(["ls", "-l"])

#執行命令,如果命令結果為0,就正常返回,否則拋異常
>>> subprocess.check_call(["ls", "-l"])
0

#接收字串格式命令,返回元組形式,第1個元素是執行狀態,第2個是命令結果 
>>> subprocess.getstatusoutput(‘ls /bin/ls‘)
(0, ‘/bin/ls‘)

#接收字串格式命令,並返回結果
>>> subprocess.getoutput(‘ls /bin/ls‘)
‘/bin/ls‘

#執行命令,並返回結果,注意是返回結果,不是列印,下例結果返回給res
>>> res=subprocess.check_output([‘ls‘,‘-l‘])
>>> res
b‘total 0\ndrwxr-xr-x 12 alex staff 408 Nov 2 11:05 OldBoyCRM\n‘

#上面那些方法,底層都是封裝的subprocess.Popen
poll()
Check if child process has terminated. Returns returncode

wait()
Wait for child process to terminate. Returns returncode attribute.


terminate() 殺掉所啟動進程
communicate() 等待任務結束

stdin 標準輸入

stdout 標準輸出

stderr 標準錯誤

pid
The process ID of the child process.

#例子
>>> p = subprocess.Popen("df -h|grep disk",stdin=subprocess.PIPE,stdout=subprocess.PIPE,shell=True)
>>> p.stdout.read()
b‘/dev/disk1 465Gi 64Gi 400Gi 14% 16901472 104938142 14% /\n‘

 

 

 

1234567891011 >>> subprocess.run(["ls""-l"])  # doesn‘t capture outputCompletedProcess(args=[‘ls‘‘-l‘], returncode=0) >>> subprocess.run("exit 1", shell=True, check=True)Traceback (most recent call last):  ...subprocess.CalledProcessError: Command ‘exit 1‘ returned non-zero exit status 1 >>> subprocess.run(["ls""-l""/dev/null"], stdout=subprocess.PIPE)CompletedProcess(args=[‘ls‘‘-l‘‘/dev/null‘], returncode=0,stdout=b‘crw-rw-rw- 1 root root 1, 3 Jan 23 16:23 /dev/null\n‘)

 

調用subprocess.run(...)是推薦的常用方法,在大多數情況下能滿足需求,但如果你可能需要進行一些複雜的與系統的互動的話,你還可以用subprocess.Popen(),文法如下:

12 = subprocess.Popen("find / -size +1000000 -exec ls -shl {} \;",shell=True,stdout=subprocess.PIPE)print(p.stdout.read())

可用參數:

    • args:shell命令,可以是字串或者序列類型(如:list,元組)
    • bufsize:指定緩衝。0 無緩衝,1 行緩衝,其他 緩衝區大小,負值 系統緩衝
    • stdin, stdout, stderr:分別表示程式的標準輸入、輸出、錯誤控制代碼
    • preexec_fn:只在Unix平台下有效,用於指定一個可執行對象(callable object),它將在子進程運行之前被調用
    • close_sfs:在windows平台下,如果close_fds被設定為True,則新建立的子進程將不會繼承父進程的輸入、輸出、錯誤管道。
      所以不能將close_fds設定為True同時重新導向子進程的標準輸入、輸出與錯誤(stdin, stdout, stderr)。
    • shell:同上
    • cwd:用於設定子進程的目前的目錄
    • env:用於指定子進程的環境變數。如果env = None,子進程的環境變數將從父進程中繼承。
    • universal_newlines:不同系統的分行符號不同,True -> 同意使用 \n
    • startupinfo與createionflags只在windows下有效
      將被傳遞給底層的CreateProcess()函數,用於設定子進程的一些屬性,如:主視窗的外觀,進程的優先順序等等

終端輸入的命令分為兩種:

  • 輸入即可得到輸出,如:ifconfig
  • 輸入進行某環境,依賴再輸入,如:python

需要互動的命令樣本

12345678910 import subprocess obj = subprocess.Popen(["python"], stdin=subprocess.PIPE, stdout=subprocess.PIPE, stderr=subprocess.PIPE)obj.stdin.write(‘print 1 \n ‘)obj.stdin.write(‘print 2 \n ‘)obj.stdin.write(‘print 3 \n ‘)obj.stdin.write(‘print 4 \n ‘) out_error_list = obj.communicate(timeout=10)print out_error_list
subprocess實現sudo 自動輸入密碼
123456789101112131415161718 import subprocess def mypass():    mypass = ‘123‘ #or get the password from anywhere    return mypass echo = subprocess.Popen([‘echo‘,mypass()],                        stdout=subprocess.PIPE,                        ) sudo = subprocess.Popen([‘sudo‘,‘-S‘,‘iptables‘,‘-L‘],                        stdin=echo.stdout,                        stdout=subprocess.PIPE,                        ) end_of_pipe = sudo.stdout print "Password ok \n Iptables Chains %s" % end_of_pipe.read() 

python subprocess模組

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在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.