2016-11-30 29 views
0

如果我正在運行在終端上的args中指定的命令,那麼它在終端上成功執行,但在python程序中執行相同的操作不起作用;我看到屏幕上的垃圾字符與輸入tar文件的大小以及許多xterm字詞相同;如何將此tar命令作爲參數傳遞給python子進程

我覺得問題在於處理參數中的''字母;

import subprocess 

try: 
    args = "cat parsing.tgz <(echo -n ''| gzip)> new-file.tgz".split() 
    subprocess.check_call(args) 
except subprocess.CalledProcessError as e: 
    print e 
+2

「不工作」是什麼意思? – Chris

+0

@Chris;我更新了我的問題,具體到您的意見。 – Viswesn

+0

關閉主題,但不是使用'split()',而應該使用['shlex.split()'](https://docs.python.org/3.5/library/shlex.html#shlex.split)。 – squiguy

回答

0

我嘗試了一些替代方案,但都沒有令人滿意。我發現最好的是切換到Popen

# this should have the a similar signature to check_call 
def run_in_shell(*args): 
    # unfortunately, `args` won't be escaped as it is actually a string argument to bash. 
    proc = subprocess.Popen(['/bin/bash', '-c', ' '.join(args)]) 
    # This will also work, though I have found users who had problems with it. 
    # proc = subprocess.Popen(' '.join(args), shell=True, executable='/bin/bash') 
    stat = proc.wait() 
    if stat != 0: 
     subprocess.CalledProcessError(returncode=stat, cmd=command) 
    return stat 

run_in_shell("cat parsing.tgz <(echo -n ''| gzip)> new-file.tgz") 

作爲說明:/bin/sh與未轉義的括號存在問題。如果你不希望上述指定'/bin/bash',則需要逃跑的括號:

args = 'cat parsing.tgz <\\(echo -n ''| gzip\\)> new-file.tgz' 
+0

問題在於args中的特殊字符'',即使是shlex也不能識別這個特殊字符viswesn @ viswesn: 〜$ python tar.py cat parsing.tgz <(echo -n''| gzip)> new-file.tgz /bin/sh:1:語法錯誤:「(」unexpected 命令'cat parsing.tgz < (echo -n''| gzip)> new-file.tgz'返回非零退出狀態2 – Viswesn

1

我不是專家,但我發現 - 此命令在sh不工作,但在工作bash

$ sh -c "cat parsing.tgz <(echo -n ''| gzip)> new-file.tgz" 
sh: -c: line 0: syntax error near unexpected token `(' 
sh: -c: line 0: `cat parsing.tgz <(echo -n ''| gzip)> new-file.tgz' 
$ 
$ bash -c "cat parsing.tgz <(echo -n ''| gzip)> new-file.tgz" 
$ 

這就是爲什麼它不直接在子過程中工作的原因。此代碼看起來工作正常:

import subprocess 
command = "cat parsing.tgz <(echo -n ''| gzip)> new-file.tgz" 
subprocess.Popen(command, shell=True, executable='/bin/bash') 
+0

是它的工作:)與bash,但我很驚訝爲什麼這不工作在:( – Viswesn

相關問題