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.

Stidgeon
  • 2,673
  • 8
  • 20
  • 28
Gosia
  • 25
  • 4
  • Does this answer your question? [append subprocess.Popen output to file?](https://stackoverflow.com/questions/7389158/append-subprocess-popen-output-to-file) – Daniel F Dec 02 '19 at 18:51

1 Answers1

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)
Mert Köklü
  • 2,183
  • 2
  • 16
  • 20
  • 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)`. – Eryk Sun Dec 02 '19 at 19:06