2016-09-30 91 views
-1

这里是进程替换的玩具的例子,在Bash中正常工作:Python的子进程不允许使用shell = True进行进程替换吗?

$ wc -l <(pwd) 
1 /proc/self/fd/11 

那么,为什么同样的命令给从Python的子带外壳时调用语法错误=真?

>>> subprocess.check_call('wc -l <(pwd)', shell=True) 
/bin/sh: 1: Syntax error: "(" unexpected 
Traceback (most recent call last): 
    File "<stdin>", line 1, in <module> 
    File "/path/to/my/python/lib/python3.5/subprocess.py", line 581, in check_call 
    raise CalledProcessError(retcode, cmd) 
subprocess.CalledProcessError: Command 'wc -l <(pwd)' returned non-zero exit status 2 
+0

'shell = True'不使用Bash。它使用'/ bin/sh'。 (我不确定这是否可配置。) – user2357112

+0

是的,这是问题所在。谢谢! –

+0

另请参阅https://stackoverflow.com/questions/5725296/difference-between-sh-and-bash究竟是什么区别。 – tripleee

回答

2

/bin/sh: 1: Syntax error: "(" unexpected

你有一个bashism。根据POSIX,这是无效的,这是/bin/sh实现的。

+2

谢谢!解决方法是用'executable ='/ bin/bash''调用'check_call'。 –

2

另一种解决方案是将更多的shell代码转移到Python本身。例如:

from subprocess import Popen, PIPE, check_call 

p1 = Popen(["pwd"], stdout=PIPE) 
p2 = check_call(["wc", "-l"], stdin=p1.stdout) 

这往往可以实现消除需要使用subprocess在所有的第一步,因为它分解工作成小块,而您可能更容易地看到如何在Python本身做。