2011-05-08 99 views
39

我想用subprocess从Python脚本运行Python脚本,我希望对每个脚本使用相同的解释器。如何从Python脚本中获取当前的Python解释器路径?

我使用的virtualenv,所以我想这样做:

subprocess.Popen('%s script.py' % python_bin) 

如何获得python_bin

它应该是在virtualenv之外的/usr/bin/python,以及在virtualenv中的/path/to/env/bin/python

回答

57

解释的名称被存储在变量sys.executable

+9

这是不可靠的嵌入式翻译,使用'os .__ file__'(礼貌http://stackoverflow.com/a/8187027/14420) – 2013-03-26 20:25:12

+1

它实际上是'os .__ file__'上的一个目录 – denfromufa 2016-03-14 02:50:15

2

只是为了确保:

>>> import sys 
>>> sys.executable 
'/usr/bin/python' 
>>> 
7

我发现它是:

>>> import sys   
>>> help(sys) 
... 

DATA 
    __stderr__ = <open file '<stderr>', mode 'w' at 0x110029140> 
    __stdin__ = <open file '<stdin>', mode 'r' at 0x110029030> 
    __stdout__ = <open file '<stdout>', mode 'w' at 0x1100290b8> 
    api_version = 1013 
    argv = [''] 
    builtin_module_names = ('__builtin__', '__main__', '_ast', '_codecs', ... 
    byteorder = 'big' 
    copyright = 'Copyright (c) 2001-2009 Python Software Foundati...ematis... 
    dont_write_bytecode = False 
    exc_value = TypeError('arg is a built-in module',) 
    exec_prefix = '/usr/bin/../../opt/freeware' 
    executable = '/usr/bin/python_64' 
相关问题