How can I make one python file run another?


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.

Asked By: Nathan Tornquist



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

Answered By: Adam Zalcman

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, 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('') in Python 2
    • exec(open('').read()) in Python 3
  3. Spawn a shell process: os.system('python'). Use when desperate.
Answered By: apc

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

  1. Put this in

    import yoursubfile
  2. Put this in

  3. Run it:

  4. It prints:


Thus runs

There are 8 ways to answer this question, A more canonical answer is here: How to import other Python files?

Answered By: Eric Leschinski
  • you can run your .py file simply with this code:

import os 

put the file in the same directory of your main python file.

Answered By: Ayser

You could use this script:

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


Answered By: xcrafter_40

It may be called from the main script as below:

import abc may be something like this:

Answered By: Alphard
from subprocess import Popen


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

Answered By: Axel Der

I used it’s almost same like subprocess.Popen

from subprocess import call
call(["python", ""])
Answered By: Samat Sadvakasov
Categories: questions Tags:
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.