This question already has an answer here:
There are more than a few ways. I’ll list them in order of inverted preference (i.e., best first, worst last):
- Treat it like a module:
import file. This is good because it’s secure, fast, and maintainable. Code gets reused as it’s supposed to be done. Most Python libraries run using multiple methods stretched over lots of files. Highly recommended. Note that if your file is called
importshould not include the
.pyextension at the end.
- The infamous (and unsafe) exec command:
execfile('file.py'). Insecure, hacky, usually the wrong answer. Avoid where possible.
- Spawn a shell process:
os.system('python file.py'). Use when desperate.
Get one python file to run another:
Put this in main.py:
#!/usr/bin/python import yoursubfile
Put this in yoursubfile.py
#!/usr/bin/python print "hello";
Thus main.py called yoursubfile.py
I’m using python 2.7.3 and Ubuntu 12.10
- you can run your .py file simply with this code:
import os os.system('python filename.py')
put the file in the same directory of your main python file.
You’d treat one of the files as a python module and make the other one import it (just as you import standard python modules). The latter can then refer to objects (including classes and functions) defined in the imported module. The module can also run whatever initialization code it needs. See http://docs.python.org/tutorial/modules.html
I used subprocess.call it’s almost same like subprocess.Popen
from subprocess import call call(["python", "your_file.py"])
You could use this script:
def run(runfile): with open(runfile,"r") as rnf: exec(rnf.read())
from subprocess import Popen Popen('python filename.py')
It may be called aa1.py from main script as below,
#!/usr/bin/python import aa1 aa1
aa1.py may be something below,