我正在开发一个程序,该程序需要调用另一个python脚本并截断当前文件的执行。我尝试使用os.close()函数执行相同的操作。如下:
def call_otherfile(self): os.system("python file2.py") #Execute new script os.close() #close Current Script
使用上面的代码,我可以打开第二个文件,但是无法关闭当前文件。我知道我很愚蠢的错误,但无法弄清楚它是什么。
为此,您将需要直接生成子流程。可以使用Unix中传统的较低级别的fork和exec模型来完成,也可以使用较高级别的API(例如)来完成subprocess
。
import subprocess
import sys
def spawn_program_and_die(program, exit_code=0):
"""
Start an external program and exit the script
with the specified return code.
Takes the parameter program, which is a list
that corresponds to the argv of your command.
"""
# Start the external program
subprocess.Popen(program)
# We have started the program, and can suspend this interpreter
sys.exit(exit_code)
spawn_program_and_die(['python', 'path/to/my/script.py'])
# Or, as in OP's example
spawn_program_and_die(['python', 'file2.py'])
另外,只需注意原始代码即可。os.close
对应于Unix syscall close
,它告诉内核您的程序不再需要文件描述符。不应将其用于退出程序。
如果您不想定义自己的函数,则总是subprocess.Popen
可以像Popen(['python', 'file2.py'])
追溯(最近一次调用):cefpython_py27.V8FunctionHandler_Execute中文件“ v8function_handler.pyx”,第48行,call_otherfile subprocess.Popen(“ python file2.py”)中的文件“ file1.py”,第62行,文件“ / System / Library / Frameworks / Python.framework / Versions / 2.7 / lib / python2.7 / subprocess.py “,第710行,init errread,errwrite)文件“ /System/Library/Frameworks/Python.framework/Versions/2.7/lib /python2.7/subprocess.py“,行_execute_child中的1335行会引发child_exception OSError:[Errno 2]没有这样的文件或目录
在使用subprocess.Popen()时遇到了以上错误,但是对于os.system()来说也可以正常工作。
尝试一下
['python', 'file2.py']
。os.system
接受您将在Shell中运行的整个命令。subprocess
将完整的argv作为列表。Popen('python file2.py')
在您的路径中寻找名为python file2.py