简体   繁体   English

如何从python脚本运行windows命令行?

[英]How to run windows command line from python script?

I have a script in Python which gives a few files but I also need a log file.我有一个 Python 脚本,它提供了一些文件,但我还需要一个日志文件。 Usually I use this command in windows cmd:通常我在windows cmd中使用这个命令:

py name.py > name.log

This script is part of a project and I need to run it from python.这个脚本是一个项目的一部分,我需要从 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.它给了我脚本准备的所有文件,但没有提供日志文件。

Use os.system使用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 :或者,您可以将 stdout 参数的打开文件句柄传递给subprocess.call

args = ['name.py']
cmd = ['py'] + args
with open('name.log', "w") as outfile:
    subprocess.call(cmd, stdout=outfile)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM