Calling a file in python
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 u开发者_如何学运维sing any of the command line tools. How should I do this?
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
execfile('foo.py')
See also:
- Further reading on execfile
import module
or __import__("module")
, to load module.py.
- Modules - Python v2.7 documentation
- Importing Python modules
精彩评论