命令在bash
中正常运行,但os.system()
正在执行/bin/sh
中的命令。
>>> os.system('echo $0')
sh
0
时/bin/sh
执行的命令失败:
[[email protected] ~]$ /bin/sh
sh-4.3$ diff -u <(echo "aba"| fold -w1) <(echo "abaa" | fold -w1)
sh: syntax error near unexpected token `('
sh-4.3$
您可以明确地在bash
运行的命令是这样的:
>>> os.system("""bash -c 'diff -u <(echo "aba"| fold -w1) <(echo "abaa" | fold -w1)'""")
--- /dev/fd/63 2017-02-26 09:18:14.633395225 +1100
+++ /dev/fd/62 2017-02-26 09:18:14.633395225 +1100
@@ -1,3 +1,4 @@
a
b
a
+a
256
既然你可以用检查可能对你通常能够输出的命令感兴趣使用subprocess.check_output()
来执行该命令并收集其输出。不幸的是,diff
在检测到输入文件中的差异时会返回非零退出代码,因此可以防止简单地使用check_output
。您可以通过管道diff
的输出通过cat
欺骗:
>>> from subprocess import check_output
>>> output = check_output(['bash', '-c', 'diff -u <(echo "aba"| fold -w1) <(echo "abaa" | fold -w1) | cat'])
>>> print(output)
b'--- /dev/fd/63\t2017-02-26 10:02:56.814044987 +1100\n+++ /dev/fd/62\t2017-02-26 10:02:56.814044987 +1100\[email protected]@ -1,3 +1,4 @@\n a\n b\n a\n+a\n'
>>> print(str(output, encoding='utf8'))
--- /dev/fd/63 2017-02-26 10:02:56.814044987 +1100
+++ /dev/fd/62 2017-02-26 10:02:56.814044987 +1100
@@ -1,3 +1,4 @@
a
b
a
+a
最好的办法是使用与管道链接在一起3'Popen'对象。 –
@ Jean-FrançoisFabre:这是真的,但这取决于你的观点。 OP询问'os.system()'。 – mhawke
我不是在批评你的答案,而是问题:) +1是我的。我应该评论这个问题,而不是答案。我不能责怪你不想用python编写3个管道! –