命令在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個管道! –