簡體   English   中英

Python subprocess.check_call問題

[英]Python subprocess.check_call issue

我知道我做錯了。

在外殼中,我將輸入:

cuebreakpoints cuefile.cue | shnsplit -o flac flacfile.flac

然后,這將根據提示文件分割flac文件。 由於我正在編寫一個小型幫助工具(使用Python)以轉換flac文件,因此我顯然想將此代碼合並到我的代碼中。

所以我用Python的方式寫道:

for root, dirs, files in os.walk(args):
    ...
    cmd = ('cuebreakpoints', cue, '|', 'shnsplit', '-o', 'flac', flacs[0])
    subprocess.check_call(cmd, cwd=None)
    ....

“ cue”是提示文件,“ flacs [0]”是flac文件。 但是我得到:

subprocess.CalledProcessError:命令'('cuebreakpoints','41_30sec.cue','|','shnsplit','-o','flac','41_30sec.flac')'返回非零退出狀態1

是否因為PIPE而出現問題?

如果要使用管道等外殼功能,則需要給check_call一個shell=True kwarg並以單個字符串形式給出命令:

check_call("cuebreakpoints '%s' | shnsplit -o flac '%s'" % (cue, flacs[0]),
           shell=True)

但請注意,如果將shell=Trueflacs消毒的cueflacs一起使用,則可能會造成安全隱患

作為將命令字符串傳遞到外殼程序的一種替代方法(並跳過了larsmans指出的安全問題),您可以創建兩個subprocess.Popen進程subprocess.Popen對象並將第一個對象的輸出連接到第二個對象的輸入(基本上就是外殼將為您做):

有關如何執行此操作的示例,請查看文檔中的“ 替換外殼程序管道”部分。

這里有一個小注解。

使用子命令編寫python腳本時,我發現shlex確實有助於解析更復雜的命令,而不必過多擔心列表的外觀。

import shlex

...
cmd = "cuebreakpoints '%s' | shnsplit -o flac '%s'" % (cue, flacs[0])
args = shlex.split(cmd)

subprocess.call(args ...)

暫無
暫無

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

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