How can I make one python file run another? [duplicate] How can I make one python file run another? [duplicate] python python

How can I make one python file run another? [duplicate]


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.


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

  1. Put this in main.py:

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

    #!/usr/bin/pythonprint("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?


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

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