简体   繁体   中英

Cannot run '>' for a terminal command in python

thanks for helping me out.

I am trying to run antiword from python to convert.docx to.doc. I have used subprocess for the task.

import subprocess
test = subprocess.Popen(["antiword","/home/mypath/document.doc",">","/home/mypath/document.docx"], stdout=subprocess.PIPE)
output = test.communicate()[0]

But it return the error,

I can't open '>' for reading
I can't open '/home/mypath/document.docx' for reading

But the same command works in terminal

antiword /home/mypath/document.doc > /home/mypath/document.docx

What am I doing wrong?

The > character is interpreted by the shell as output stream redirection. However, subprocess doesn't use a shell, so there is nothing to interpret the > character as redirection. Hence the > character will be passed on to the command. After all, it is a perfectly-legal filename: how is subprocess supposed to know you don't actually have a file named > ?

It's not clear why you are attempting to redirect the output of antiword to a file and also read the output in the variable output . If it's redirected to a file, there will be nothing to read in output .

If you want to redirect the output of a subprocess call to a file, open the file for writing in Python and pass the opened file to 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]

It's possible that the process may write to its standard error stream, so I've captured anything that gets written to that in the variable error .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM