繁体   English   中英

在Windows 7上从另一个python脚本运行python脚本

[英]running python script from another python script on Windows 7

有一个线性python脚本:

# inner.py
print "hello"

当我创建另一个脚本时:

import os
os.system('python inner.py > out.txt')

并从命令行执行它,一切按预期进行,“ hello”写入out.txt

当我用以下命令替换os.system参数时:

os.system('inner.py > out.txt')

并执行脚本,出现以下错误:

close failed in file object destructor:
Error in sys.excepthook:

Original exception was:

如果不重定向输出,两种情况下都会在控制台上显示“ hello”。

我在Windows 7 64位上。

为什么会出现错误?

改用execfile函数:

execfile('inner.py') # in the outer script

如果要重定向文件的输出,请使用subprocess.check_call并将标准输出重定向到文件对象:

from subprocess import check_call

with open("out.txt",'w') as f:
    check_call(["python", "/path/to/inner.py"], stdout=f)

除非您将sys.stdout重定向到文件对象,否则它不适用于您的打印示例,但是,如果您实际上具有在另一个模块中返回某些内容的函数,则可以导入它们,然后将输出写入文件而无需使用子进程。

暂无
暂无

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

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