How can I make one python file to run another?
For example I have two .py files. I want one file to be run, and then have it run the other .py file.
Use the execfile() Method to Run a Python Script in Another Python Script. The execfile() function executes the desired file in the interpreter. This function only works in Python 2. In Python 3, the execfile() function was removed, but the same thing can be achieved in Python 3 using the exec() method.
Using terminal - this is the simplest way to do it . You execute any python script as “$python a.py”. Now, if you want multiple scripts, you can either open up multiple terminals and run diffent programs on each or, in the same terminal “$ python a.py&b.py&c.py” . This will execute all programs from the same terminal.
There are more than a few ways. I'll list them in order of inverted preference (i.e., best first, worst last):
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 file.py
, your import
should not include the .py
extension at the end.execfile('file.py')
in Python 2exec(open('file.py').read())
in Python 3os.system('python file.py')
. Use when desperate.Put this in main.py:
#!/usr/bin/python import yoursubfile
Put this in yoursubfile.py
#!/usr/bin/python print("hello")
Run it:
python main.py
It prints:
hello
Thus main.py
runs yoursubfile.py
There are 8 ways to answer this question, A more canonical answer is here: How to import other Python files?
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With