1

I'm modifying someone else's Python code, and it currently synchronously executes an external Python script (fast-downward) using the system's default Python (and gets the return code):

code = os.system("%s/src/translate/translate.py %s %s" % (down_home, domain, pddl) # ...

I don't want to make /usr/local/bin/python2.7 my default Python interpreter (CentOS ships with an older Python). How can I invoke an external Python script using the current Python interpreter?

I don't want to fork. I'll try the suggestion, but I need the return code.

Peter Mortensen
  • 30,738
  • 21
  • 105
  • 131
Daniel
  • 855
  • 10
  • 21
  • EDIT: I don't want to fork. I'll try the suggestion but I need the return code. – Daniel Jan 20 '14 at 20:37
  • Have you tried the `import` syntax as documented here: http://docs.python.org/2/tutorial/modules.html? – Dan Bechard Jan 20 '14 at 20:38
  • I haven't because I don't know if calling a function (assuming I can identify the right function to call) in the script will have the same behavior as executing the script. – Daniel Jan 20 '14 at 20:42
  • 1
    Perhaps this will help you: http://docs.python.org/2/library/subprocess.html#subprocess.check_output%20%60subprocess.check_output%28%29%60 – Dan Bechard Jan 20 '14 at 20:44
  • I'm not sure how that solves the problem any differently, seems like an extra step, but if it ain't broke.. – Dan Bechard Jan 20 '14 at 20:57

3 Answers3

1

This should be it:

import subprocess, sys
subprocess.call([sys.executable, ...])
User
  • 14,131
  • 2
  • 40
  • 59
1

You could use check_call from subprocess you can get the returned value and it raises if the return code is not zero.

El Bert
  • 2,958
  • 1
  • 28
  • 36
1

You might just want to use virtualenv with the new interpreter. You can install the new Python, but don't make it the primary system Python. Or maybe you already have Python 2.7 installed.

https://github.com/0xdata/h2o/wiki/Installing-python-2.7-on-centos-6.3.-Follow-this-sequence-exactly-for-centos-machine-only

Then

pip install virtualenv
virtualenv venv --distribute -p /usr/local/bin/python2.7
source venv/bin/activate

Now your path will be adjusted to the local venv directory, containing the new Python. You can install dependencies, etc., and they will only be installed into venv. This is a great way to isolate your environments from each other.

Peter Mortensen
  • 30,738
  • 21
  • 105
  • 131
jhorman
  • 466
  • 3
  • 5