I tried such code to redirect standart output to the file:
subprocess.Popen('my command', cwd='my path', shell=True, stdout=stdout.txt, stderr=stdout.txt)
But got error: NameError: name 'stdout' is not defined
I use python version 2.5.2
Open the file first and use a to append if you want to keep a record of all output/errors or use w to overwrite each time:
with open("stdout.txt","a+") as stdout:
subprocess.Popen('my command', cwd='my path', shell=True, stdout=stdout, stderr=stdout)
Using with will automatically close your file.
Popen doesn't block until my command completes, though, so ensure you don't leave the with statement before the command completes.AttributeError: 'str' object has no attribute 'fileno' shell=True? Understandably it's matching the OP exact code. But I came across this answer to help out someone else, and having shell != True would probably be more appropriate for a more robust solution.
stdoutargument could take a file name instead of a file handle (note: it can't), you would have to quote the text. As it is, Python thinks you are trying to access thetxtattribute of an object referenced bystdout, not specifying a file name of "stdout.txt".