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.

2
  • 1
    First of all use a raw string. Commented Aug 8, 2013 at 15:52
  • 1
    "got nothing"? Not even an error message? Commented Aug 8, 2013 at 15:53

4 Answers 4

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
Sign up to request clarification or add additional context in comments.

Comments

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)

1 Comment

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.
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.

Comments

1

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

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.