52

I have a Pylons controller (irrelevant but explains why I have this need) say starter.py that starts another process using:

retcode = subprocess.call(('python','/path/to/myScript.py'))

now since the app runs in a virtual env python is not the right binary to call since it has no access to site-packages installed in my virtual env.

It should be instead:

retcode = subprocess.call(('path/to/virtual/env/bin/python','/path/to/myScript.py'))

and path/to/virtual/env/bin/python is the same that is running starter.py.

Any chance to not set this path (say, in a .ini file) and retrieve it?

neurino
  • 11,500
  • 2
  • 40
  • 63

1 Answers1

106

The path is available in sys.executable.

Sven Marnach
  • 574,206
  • 118
  • 941
  • 841
  • 2
    The fastest answer ever, I'll accept when I'll be allowed to. Thanks – neurino Mar 01 '11 at 13:27
  • I've found one edge case where this isn't true -- the built-in Python in Sublime Text 3, for which sys.executable is simply `python3` – Paul Bissex Aug 03 '15 at 13:17
  • 1
    @PaulBissex: For embeded interpeters, there might not even exist a standalone Python binary, so there's not much you can do for these cases. In general, it's probably preferable to try and run Python code within the current interpreter instead of forking to a sub-interpreter. – Sven Marnach Aug 04 '15 at 13:57
  • @SvenMarnach What if the file is self-executing? Let's say `myScript.py` has been compiled to `myScript.exe` ? – TSR Aug 03 '18 at 19:17
  • @TSR I've never done that (I don't use Windows), so I can't tell for sure. However, the linked documentation indicates that `sys.executable` will be either `None` or an empty string in that case. – Sven Marnach Aug 03 '18 at 19:44
  • In my case ```which python3``` worked in macOS command line. – Saurabh Gupta May 26 '23 at 08:47