436

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.

5

8 Answers 8

674

There are more than a few ways. I'll list them in order of inverted preference (i.e., best first, worst last):

  1. 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 file.py, your import should not include the .py extension at the end.
  2. The infamous (and unsafe) exec command: Insecure, hacky, usually the wrong answer. Avoid where possible.
    • execfile('file.py') in Python 2
    • exec(open('file.py').read()) in Python 3
  3. Spawn a shell process: os.system('python file.py'). Use when desperate.
Sign up to request clarification or add additional context in comments.

22 Comments

just to add a bit of detail to case #1: say you want to import fileB.py into fileA.py. assuming the files are in the same directory, inside fileA you'd write import fileB. then, inside fileA, you can call any function inside fileB like so: fileB.name_of_your_func(). there's more options and details of course, but this will get you up and running.
Use subprocess module instead of os module
Using import adds namespacing to the functions, e.g. function() becomes filename.function(). To avoid this use "from name import *". This will also run the code body. Running with os.system() will not keep the defined function (as it was run in another process). execfile is exec() in Python 3, and it doesn't work.
execfile worked :D
I was interested in how to define arguments to the other .py script using "import()"
|
85

Get one python file to run another, using python 2.7.3 and Ubuntu 12.10:

  1. Put this in main.py:

    #!/usr/bin/python
    import yoursubfile
    
  2. Put this in yoursubfile.py

    #!/usr/bin/python
    print("hello")
    
  3. Run it:

    python main.py 
    
  4. 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?

7 Comments

Make sure that we do not use "." (dot) in the imported python script file name
Not "import subfile.py" Just "import subfile" despite filename is subfile.py
Oh please get rid of the semicolon. As a recovering C/C++ programmer it hurts my eyes!
How to pass arguments to yoursubfile.py ?
@AgnelVishal to pass command-line arguments to the script, you could edit sys.argv list.
|
49

I used subprocess.call it's almost same like subprocess.Popen

from subprocess import call
call(["python", "your_file.py"])

6 Comments

Please add explanations to your answer.
getting "NameError: name 'python' is not defined"
@Tahlor add the python.exe directory to your PATH variable in Environment Variables
@Tahlor, add shell=True
How do I break the execution of the program if there's an infinite loop like in messaging then?
|
35
  • 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.

4 Comments

Does this spawn another process?
Doesn't always work. -1
@CristiFati When doesn't it work?
@Moondra Yes, this method does spawn another process, at least on Windows. On the other hand, importing the file does not. [Tested it by running tasklist | findstr "python" in cmd]
18
from subprocess import Popen

Popen('python filename.py')

or how-can-i-make-one-python-file-run-another-file

4 Comments

Exactly I was looking for. All the other answers ` import secondary exec(open('secondary.py').read()) os.system('python secondary.py') call(["python", "secondary.py"]) ` they don't allow creating multiple instances of the secondary python file at the same time. They all wait for the execution to finish only then you can call that file again. Only Popen allows multiple async calls. Thanks again.
Say if there is a def func1() within filename.py, then how to just run this particular function only under Popen('python filename.py') approach?
on python3 i needed to use Popen(['python3', 'filename.py'])
I get OSError: [WinError 193] %1 is not a valid Win32 application with this solution. See stackoverflow.com/questions/25651990/…
6

You could use this script:

def run(runfile):
  with open(runfile,"r") as rnf:
    exec(rnf.read())

Syntax:

run("file.py")

4 Comments

What's the logic behind this?
Super late response, but it basically takes a file (variable runfile), opens it, reads the contents of it. (contents are read in the rnf.read() function) those contents are then executed as python code, hence the exec() call. Information on exec can be found here
But what is the logic of doing it in this way instead of simply exec("file.py") per this answer?
You probably mean execfile("file.py"), and it isn't supported as of Python 3.
3

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

Comments

-1

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'

1 Comment

I think line: aa1 is pointless, the file is run when you import it

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.