温馨提示:本文翻译自stackoverflow.com,查看原文请点击:其他 - How to execute another python file and then close the existing one?
file python python-2.7 python-os

其他 - 如何执行另一个python文件,然后关闭现有的文件?

发布于 2020-03-27 10:17:00

我正在开发一个程序,该程序需要调用另一个python脚本并截断当前文件的执行。我尝试使用os.close()函数执行相同的操作。如下:

def call_otherfile(self): os.system("python file2.py") #Execute new script  os.close() #close Current Script  

使用上面的代码,我可以打开第二个文件,但是无法关闭当前文件。我知道我很愚蠢的错误,但无法弄清楚它是什么。

查看更多

提问者
OshoParth
被浏览
295
Edward Minnix 2019-07-03 21:38

为此,您将需要直接生成子流程。可以使用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'])