如何执行另一个python文件,然后关闭现有文件?
我正在编写一个程序,该程序需要调用另一个python脚本并截断当前文件的执行。我尝试使用os.close()函数执行同样的操作。详情如下:如何执行另一个python文件,然后关闭现有文件?,python,python-2.7,file,python-os,Python,Python 2.7,File,Python Os,我正在编写一个程序,该程序需要调用另一个python脚本并截断当前文件的执行。我尝试使用os.close()函数执行同样的操作。详情如下: def call_otherfile(self): os.system("python file2.py") #Execute new script os.close() #close Current Script 使用上述代码,我可以打开第二个文件,但无法关闭当前文件。我知道我犯了一个愚蠢的错误,但无法找出原因。使用模块,这是执行此类
def call_otherfile(self):
os.system("python file2.py") #Execute new script
os.close() #close Current Script
使用上述代码,我可以打开第二个文件,但无法关闭当前文件。我知道我犯了一个愚蠢的错误,但无法找出原因。使用模块,这是执行此类操作的建议方法(执行新脚本、流程),特别要注意启动新进程和终止当前程序的方法。要执行此操作,您需要直接生成子进程。这既可以使用较低级别的fork和exec模型(在Unix中是传统的)来完成,也可以使用更高级别的API(如API)来完成 另外,只需在原始代码上做一个注释
os.close
对应于Unix系统调用close
,它告诉内核您的程序不再需要文件描述符。它不应该用于退出程序
如果你不想定义自己的函数,你可以直接调用
subprocess.Popen
,就像Popen(['python','file2.py'])
这在什么操作系统上运行?目前在MAC上,但我需要一个通用的解决方案。OS.system()
在第二个脚本完成之前不会完成。您希望os.execv()
(或其变体之一)用第二个脚本的执行来替换当前脚本。您是否可以参考一些详细的文档或至少一些示例…?回溯(最近一次调用):文件“v8function\u handler.pyx”,第48行,在cefpython_py27.V8FunctionHandler\u执行文件“file1.py”中,第62行,在call_otherfile subprocess.Popen(“python file2.py”)文件“/System/Library/Frameworks/python.Frameworks/python.Frameworks/lib/python2.7/subprocess.py”中,第710行,在init errread,errwrite)文件“/System/Library/Frameworks/python2.7/subprocess.py”中,第1335行,在_execute_child raise child_exception OSError:[Errno 2]中,没有这样的文件或目录在使用subprocess.Popen()时出现上述错误,但是在os.system()中也可以正常工作。请使用['python','file2.py']
尝试os.system
接受您将在shell中运行的整个命令<代码>子流程将完整的argv作为列表Popen('python file2.py')
正在您的路径上查找名为python file2.py的程序
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'])