5

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

1
  • Assuming the stdout argument 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 the txt attribute of an object referenced by stdout, not specifying a file name of "stdout.txt". Commented Jul 28, 2014 at 14:08

2 Answers 2

8

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.

Sign up to request clarification or add additional context in comments.

7 Comments

Popen doesn't block until my command completes, though, so ensure you don't leave the with statement before the command completes.
I try this, but got AttributeError: 'str' object has no attribute 'fileno'
How are you using it exactly
Hi @PadraicCunningham. Thoughts on maybe adding the suggestion (or show an alternative solution) to this solution to not use 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.
@idjaw, hi, I will update with a few more options tomorrow. A s far as shell=True goes it actually depends on what you are running, for windows you actually need it.
|
1

Give a file descriptor to stdout See doc

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.