tags:

views:

66

answers:

3

Hello,

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?

+4  A: 
execfile('foo.py')

See also:

jathanism
+3  A: 

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
unutbu
+1: Seems like overkill but I like it anyways. :)
jathanism
@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.
unutbu
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.
jathanism
+1  A: 

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

Propeng