簡體   English   中英

如何使用python中的子進程獲取退出狀態?

[英]How to get exit status using subprocess in python?

我必須通過python腳本運行“提交”命令,並根據其退出或返回狀態打印一條消息。

代碼如下:

import subprocess

msg = 'summary about commit'
commitCommand = 'hg commit -m "{}"'.format(msg)

p = subprocess.Popen(commitCommand, stdout=subprocess.PIPE)
output = p.communicate()[0]

if p.returncode:
    print 'commit failed'
    sys.exit()
else:
    print 'Commit done'

這給了我以下錯誤:

Traceback (most recent call last):
  File "script.py", line 66, in <module>
    p = subprocess.Popen(commitCommand, stdout=subprocess.PIPE)
  File "/usr/lib/python2.7/subprocess.py", line 711, in __init__
    errread, errwrite)
  File "/usr/lib/python2.7/subprocess.py", line 1308, in _execute_child
    raise child_exception
OSError: [Errno 2] No such file or directory

如何糾正這個錯誤?

從文檔;

args應該是程序參數的序列,或者是單個字符串。 默認情況下,如果args是序列,則要執行的程序是args中的第一項。 如果args是字符串,則解釋取決於平台,並在下面進行描述。 有關默認行為的其他區別,請參見shell和可執行參數。 除非另有說明,否則建議將args作為序列傳遞。

在Unix上,如果args是字符串,則將該字符串解釋為要執行的程序的名稱或路徑。 但是,只有在不將參數傳遞給程序的情況下才能執行此操作。

因此,它正在尋找文件hg commit -m "{}".format(msg) Popen想要一個列表,第一個元素是“ hg”,或者更好的是真實路徑。

或在Popen中設置shell = True (全部來自文檔,不假裝實際上經常進行測試)並獲得Popen(['/bin/sh', '-c', args[0], args[1], ...])效果。

Bakuriu的評論建議是一個不錯的選擇,但請使用shlex。

前述過程使用起來更安全...但是另外,會有骯臟的方式來做任何事情...

除了將命令拆分為字符串數組之外,您還可以將shell=Truestdout = subprocess.PIPE.一起使用stdout = subprocess.PIPE.

但這就是python關於使用shell = True.說法shell = True.

Warning Passing shell=True can be a security hazard if combined with untrusted input. See the warning under Frequently Used Arguments for details.

如果您未使用shell = True並在字符串中給出命令,則會拋出上述錯誤,因為它查找的第一個命令是shell路徑,而您傳遞的hg不存在。
但是明智地使用shell = True

PS請注意,您已被警告:P

您沒有使用shell=True ,在這種情況下,您需要將命令及其准備好的參數作為列表傳遞:

commitCommand = ['hg', 'commit', '-m', msg]

這也意味着您無需引用該消息。 僅在使用外殼程序並且您要將整個消息作為一個參數傳遞時才需要。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM