2

I'd like to call a .py file from within python. It is in the same directory. Effectivly, I would like the same behavior as calling python foo.py from the command line without using any of the command line tools. How should I do this?

3 Answers 3

4

It's not quite clear (at least to me) what you mean by using "none of the command-line tools".

To run a program in a subprocess, one usually uses the subprocess module. However, if both the calling and the callee are python scripts, there is another alternative, which is to use the multiprocessing module.

For example, you can organize foo.py like this:

def main():
    ...

if __name__=='__main__':
    main()

Then in the calling script, test.py:

import multiprocessing as mp
import foo
proc=mp.Process(target=foo.main)
proc.start()
# Do stuff while foo.main is running
# Wait until foo.main has ended
proc.join()    
# Continue doing more stuff
Sign up to request clarification or add additional context in comments.

2 Comments

@jathanism: That's quite possible :) Though, I like calling functions (which mp.Process allows) much more than calling python scripts (through subprocess) which then need to be optparsed/argparsed.
I don't disagree with you. I am only just now getting into multiprocessing and I'm happy to see such a basic usage of it.
4
execfile('foo.py')

See also:

Comments

3

import module or __import__("module"), to load module.py.

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.