[英]Cannot run '>' for a terminal command in python
謝謝你的協助。
我正在嘗試運行 antiword 從 python 到 convert.docx to.doc。 我已經為任務使用了子流程。
import subprocess
test = subprocess.Popen(["antiword","/home/mypath/document.doc",">","/home/mypath/document.docx"], stdout=subprocess.PIPE)
output = test.communicate()[0]
但它返回錯誤,
I can't open '>' for reading
I can't open '/home/mypath/document.docx' for reading
但是相同的命令在終端中有效
antiword /home/mypath/document.doc > /home/mypath/document.docx
我究竟做錯了什么?
>
字符被 shell 解釋為 output stream 重定向。 但是, subprocess
進程不使用 shell,因此沒有什么可以將>
字符解釋為重定向。 因此>
字符將傳遞給命令。 畢竟,這是一個完全合法的文件名: subprocess
如何知道您實際上沒有名為>
的文件?
目前尚不清楚您為什么要嘗試將反詞的antiword
重定向到一個文件,並在變量 output 中讀取output
。 如果它被重定向到一個文件,則output
中將沒有任何內容可讀。
如果要將subprocess
進程調用的 output 重定向到文件,請在 Python 中打開文件進行寫入,並將打開的文件傳遞給subprocess.Popen
:
with open("/home/mypath/document.docx", "wb") as outfile:
test = subprocess.Popen(["antiword","/home/mypath/document.doc"], stdout=outfile, stderr=subprocess.PIPE)
error = test.communicate()[1]
該進程可能會寫入其標准錯誤 stream,因此我已經在變量error
中捕獲了寫入該錯誤的所有內容。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.