Solving problem is about exposing yourself to as many situations as possible like How can I make one python file run another? [duplicate] and practice these strategies over and over. With time, it becomes second nature and a natural way you approach any problems in general. Big or small, always start with a plan, use other strategies mentioned here till you are confident and ready to code the solution.
In this post, my aim is to share an overview the topic about How can I make one python file run another? [duplicate], which can be followed any time. Take easy to follow this discuss.
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.
Answer #1:
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 calledfile.py
, yourimport
should not include the.py
extension at the end. - The infamous (and unsafe) exec command: Insecure, hacky, usually the wrong answer. Avoid where possible.
execfile('file.py')
in Python 2exec(open('file.py').read())
in Python 3
- Spawn a shell process:
os.system('python file.py')
. Use when desperate.
Answer #2:
Get one python file to run another, using python 2.7.3 and Ubuntu 12.10:
-
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?
Answer #3:
I used subprocess.call it’s almost same like subprocess.Popen
from subprocess import call
call(["python", "your_file.py"])
Answer #4:
- you can run your .py file simply with this code:
import os
os.system('python filename.py')
note:
put the file in the same directory of your main python file.
Answer #5:
from subprocess import Popen
Popen('python filename.py')
Answer #6:
You could use this script:
def run(runfile):
with open(runfile,"r") as rnf:
exec(rnf.read())
Syntax:
run("file.py")
Answer #7:
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
Answer #8:
It may be called abc.py
from the main script as below:
#!/usr/bin/python
import abc
abc.py
may be something like this:
print'abc'