Warm tip: This article is reproduced from stackoverflow.com, please click
file python python-2.7 python-os

How to execute another python file and then close the existing one?

发布于 2020-03-27 10:15:01

I am working on a program that requires to call another python script and truncate the execution of the current file. I tried doing the same using the os.close() function. As follows:

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

Using the above code I am able to open the second file but am unable to close the current one.I know I am silly mistake but unable to figure out what's it.

Edward Minnix 2019-07-03 21:38

To do this you will need to spawn a subprocess directly. This can either be done with a more low-level fork and exec model, as is traditional in Unix, or with a higher-level API like 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
    # We have started the program, and can suspend this interpreter

spawn_program_and_die(['python', 'path/to/my/script.py'])

# Or, as in OP's example
spawn_program_and_die(['python', 'file2.py'])

Also, just a note on your original code. os.close corresponds to the Unix syscall close, which tells the kernel that your program that you no longer need a file descriptor. It is not supposed to be used to exit the program.

If you don't want to define your own function, you could always just call subprocess.Popen directly like Popen(['python', 'file2.py'])