0

I am trying to call a python script in another python script. The directories are different. I tried

import subprocess
subprocess.call("C:\temp\hello2.py", shell=True)

But got nothing. It does not work. I reviewed many forums, but all of them are about calling it when both scripts are on the same directory.

I tried having both scripts in the same directory. In this case, I can run the model in the Python.exe (through cmd window) but not in IDLE. In IDLE, I do not even get an error message.

I really need to do that, such that I can't define the other script as a different module, etc. I need to call a script in another script.

Sukrit Kalra
  • 33,167
  • 7
  • 69
  • 71
Ege Ozlem
  • 903
  • 2
  • 9
  • 8

4 Answers4

6

Escape backslash (\)

"C:\\temp\\hello2.py"

or use raw string

r"C:\temp\hello2.py"

>>> print "C:\temp\hello2.py"
C:      emp\hello2.py
>>> print "C:\\temp\\hello2.py"
C:\temp\hello2.py
>>> print r"C:\temp\hello2.py"
C:\temp\hello2.py
falsetru
  • 357,413
  • 63
  • 732
  • 636
2

First the backslash thing, and second you should always call python scripts with the python interpreter. You never know what are *.py files associated with. So:

import sys
import subprocess
subprocess.call([sys.executable, 'C:\\temp\\hello2.py'], shell=True)
Viktor Kerkez
  • 45,070
  • 12
  • 104
  • 85
  • Although sometimes appropriate, this is not true if you want to call 3rd party python modules that expect a different python version. The system registered python is not necessarily a bad thing. – tdelaney Aug 08 '13 at 20:00
1

I'm not sure what you mean by 'I can't define the other script as a different module, etc. I need to call a script in another script.', but I think you can avoid the whole subprocess business by just importing your other python script, as in this answer.

i.e.

import imp

hello2 = imp.load_source("hello2", 'C:\temp\hello2.py')

That should run your hello2.py script - sorry if I'm misunderstanding the constraints of your situation.

Community
  • 1
  • 1
Brionius
  • 13,858
  • 3
  • 38
  • 49
1

I think we can go for an approach by altering the sys.path list.

import sys
sys.path.append("C:\\temp\\")
import hello2