【问题标题】:How to execute another python file and then close the existing one?如何执行另一个python文件然后关闭现有的?
【发布时间】:2019-11-14 03:39:55
【问题描述】:

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

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

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

【问题讨论】:

  • 这是在什么操作系统上运行的?
  • 现在在 MAC 但我需要一个通用的解决方案。
  • os.system() 在第二个脚本完成之前不会完成。您希望 os.execv()(或其变体之一)将当前脚本替换为执行第二个脚本。
  • 您能否参考一些详细的文档或至少一些示例......?

标签: python python-2.7 file python-os


【解决方案1】:

使用 os.startfile 非常简单,然后使用 exit() 或 sys.exit() 它将 100% 工作 #file 1 os.startfile("file2.py") exit()

【讨论】:

    【解决方案2】:

    为此,您需要直接生成一个子进程。这可以使用更底层的 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'])
    

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

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

    【讨论】:

    • 回溯(最近一次调用最后):文件“v8function_handler.pyx”,第 48 行,在 cefpython_py27.V8FunctionHandler_Execute 文件“file1.py”,第 62 行,在 call_otherfile subprocess.Popen("python file2. py") 文件 "/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",第 1335 行,在 _execute_child raise child_exception OSError: [Errno 2] No such file or directory
    • 在使用 subprocess.Popen() 时出现上述错误,但同样适用于 os.system()。
    • 试试['python', 'file2.py']os.system 获取您将在 shell 中运行的整个命令。 subprocess 将完整的 argv 作为列表。 Popen('python file2.py') 正在您的路径上寻找名为 python file2.py 的程序
    【解决方案3】:

    使用subprocess 模块,这是执行此类工作(执行新脚本、进程)的建议方法,特别是查看Popen 以启动新进程并终止您可以使用的当前程序@ 987654323@.

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2017-12-27
      • 2021-06-03
      • 1970-01-01
      • 1970-01-01
      • 2013-11-21
      • 1970-01-01
      • 2013-02-24
      • 1970-01-01
      相关资源
      最近更新 更多