58

I want to run a Python script from a Python script with subprocess, and I wish to do it using the same interpreter for each of them.

I'm using virtualenv, so I'd like to do something like:

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

How do I get python_bin?

It should be /usr/bin/python outside a virtualenv, and /path/to/env/bin/python in a virtualenv.

Peter Mortensen
  • 30,738
  • 21
  • 105
  • 131
Bite code
  • 578,959
  • 113
  • 301
  • 329

3 Answers3

77

The name of the interpreter is stored in the variable sys.executable

Bryan Oakley
  • 370,779
  • 53
  • 539
  • 685
Ignacio Vazquez-Abrams
  • 776,304
  • 153
  • 1,341
  • 1,358
7

I found it by:

>>> 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'
nemo
  • 12,241
  • 3
  • 21
  • 26
5

Just for making sure:

>>> import sys
>>> sys.executable
'/usr/bin/python'
>>>
Peter Mortensen
  • 30,738
  • 21
  • 105
  • 131
Yuda Prawira
  • 12,075
  • 10
  • 46
  • 54