Search code examples
pythonpython-3.xdoc

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 ?


Solution

  • 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.