1

I have a script in Python which gives a few files but I also need a log file. Usually I use this command in windows cmd:

py name.py > name.log

This script is part of a project and I need to run it from python. I tried this:

subprocess.call(["py","name.py",">","name.log"])

And it give me all the files that the script prepares but not the log file.

1

1 Answer 1

3

Use os.system

os.system("py name.py > name.log")

Or, you can just pass an open file handle for the stdout argument to subprocess.call:

args = ['name.py']
cmd = ['py'] + args
with open('name.log', "w") as outfile:
    subprocess.call(cmd, stdout=outfile)
Sign up to request clarification or add additional context in comments.

1 Comment

Note that when writing to a file or pipe, Windows Python uses the system ANSI codepage by default, which may result in encoding errors. You can override the encoding of standard I/O to UTF-8, e.g. environ = os.environ.copy(); environ['PYTHONIOENCODING'] = 'utf-8'; subprocess.call(cmd, stdout=outfile, env=environ).

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.