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

Osh*_*rth 2 python file python-2.7 python-os

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

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

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

Edw*_*nix 8

为此,您需要直接生成一个子进程。这可以使用更底层的 fork 和 exec 模型来完成(如 Unix 中的传统),也可以使用更高级别的 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'])
Run Code Online (Sandbox Code Playgroud)

另外,请注意您的原始代码。os.close对应于 Unix 系统调用close,它告诉内核您的程序不再需要文件描述符。它不应该用于退出程序。

如果你不想定义自己的函数,你可以直接subprocess.Popen调用Popen(['python', 'file2.py'])