【问题标题】:Run python script from another python script but not as an child process从另一个 python 脚本运行 python 脚本,但不作为子进程运行
【发布时间】:2015-12-21 10:38:31
【问题描述】:

是否可以在不等待终止的情况下从另一个 python 脚本运行 python 脚本。

父进程将在子进程创建后立即终止。

我试过了:

subprocess.Popen([sys.executable, "main.py"], stdout=subprocess.PIPE, stderr=subprocess.PIPE, stdin=subprocess.PIPE)

还有:

os.system(...)

【问题讨论】:

    标签: python unix process


    【解决方案1】:

    如果您知道其他 Python 脚本具有 main 方法,您可以简单地在代码中调用该其他脚本:

    import main
    ...
    exit(main.main())
    

    但是这里的另一个脚本是在调用脚本的上下文中执行的。如果你想避免它,你可以使用 os.exec... 函数,通过启动一个新的 Python 解释器:

    import os
    ...
    os.execl(sys.executable, "python", 'main.py')
    

    exec 系列函数将(在 Unix-Linux 下)用新的 Python 解释器替换当前的 Python 解释器。

    【讨论】:

      【解决方案2】:

      您只需添加& 即可在后台启动脚本:

      import os
      
      os.system('/path/to/script.sh &')
      
      exit()
      

      在这种情况下,即使在主要 Python 脚本退出后,启动的 shell 脚本也会继续工作。 但请记住,它可能会导致我们系统中出现僵尸进程。

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2016-09-03
        • 1970-01-01
        • 1970-01-01
        • 2017-03-30
        • 1970-01-01
        • 1970-01-01
        • 2023-03-20
        • 1970-01-01
        相关资源
        最近更新 更多