2017-05-31 46 views
0

好像它在兩個地方中斷,一個是「>」,二是「/ tmp/testing」。爲什麼「>」在python2中的subprocess.call中不起作用

Python 2.7.5 (default, Aug 29 2016, 10:12:21) 
[GCC 4.8.5 20150623 (Red Hat 4.8.5-4)] on linux2 
Type "help", "copyright", "credits" or "license" for more information. 
>>> import subprocess 
>>> subprocess.call(["ls", "-ltr", ">", "/tmp/testing"]) 
ls: cannot access >: No such file or directory 
ls: cannot access /tmp/testing: No such file or directory 
2 
>>> exit() 

我GOOGLE了,並找到其他方式來實現我所需要的。

with.open("/tmp/testing","w") as f: 
    subprocess.call(["ls", "-ltr"], stdout=f) 

想知道爲什麼第一個腳本不起作用。

+0

因爲「>」是shell命令(bash,sh或其他的東西)。/bin/ls本身並不知道有關'>'或'|'的任何信息,等 – Eugene

+0

謝謝@Eugene它是有道理的! –

回答

1

您試圖用來重定向ls的輸出的>由您的shell實現,而不是由ls本身實現。當您使用subprocess.call時,它(默認情況下)不使用shell來運行程序。您可以通過傳遞shell=True作爲參數來改變它(您可能還需要更改命令的傳遞方式)。

或者,您可以使用Python代碼而不是shell來自行處理輸出到文件的重定向。試試這樣:

with open('/tmp/testing', 'w') as out: 
    subprocess.call(['ls', '-ltr'], stdout=out) 
+0

非常感謝! –

相關問題