调用 Python 脚本作为子进程 [英] Invoking Python Script as Subprocess

查看:31
本文介绍了调用 Python 脚本作为子进程的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在围绕一些 python 脚本创建一个包装器,并且在计算机上安装了多个版本的 python 时遇到了一个小问题.例如,在我的 Mac 上,python 2.7 可以通过命令行中的python"访问,python 3.4 可以通过python3"访问.无论如何确定当前 python 实例是如何启动的,以便我可以确定子进程将使用正确的版本?

I am creating a wrapper around a few python scripts and have run into a slight issue when there are multiple versions of python installed on the computer. For example on my Mac there is python 2.7 accessible via "python" at the command line and python 3.4 available "python3". Is there anyway to determine how the current python instance was started so that I can be sure the subprocess will be using the right version?

import subprocess

def main():
    pythonCommand = determineCommand() #What is python install as on this computer
    argArray = [pythonCommand, "test.py"] #requires python 3.4
    subprocess.call(argArray)

#What I need to figure out
def determineCommand():
    #If Some Check
        return "python3"
    #Else some other check
        return "python"
    #else something weird
        return "python34"
    #and so on

if __name__ == "__main__":
    main()

以上代码在我的电脑上无法正常执行,但在仅安装了 python 3.4 的电脑上运行正常.更改 argArray 以使用 python3 可以在我的计算机上运行,​​但在其他计算机上会中断.

The above code will not execute properly on my computer but on a computer with only python 3.4 installed it works fine. Changing the argArray to use python3 works on my computer but breaks it on others.

推荐答案

要获取用于启动当前 Python 解释器的可执行文件,请阅读 sys.executable.它是当前运行的 Python 解释器二进制文件的绝对路径(尽管在奇怪的情况下它可以是空字符串或 None,例如冻结的可执行文件等).

To get the executable used to launch the current Python interpreter, read sys.executable. It's the absolute path to the Python interpreter binary currently running (though it can be the empty string or None in weird cases, like frozen executables and the like).

这篇关于调用 Python 脚本作为子进程的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆