424

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.

wj127
  • 118
  • 1
  • 12
Nathan Tornquist
  • 6,468
  • 10
  • 47
  • 72

8 Answers8

644

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.
Christian Rauch
  • 86
  • 3
  • 10
apc
  • 6,723
  • 1
  • 15
  • 10
  • 95
    **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. – jon May 06 '14 at 21:20
  • 28
    Use `subprocess` module instead of `os` module – Hannes Karppila Jun 10 '15 at 16:19
  • 10
    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. – CoderGuy123 Aug 12 '15 at 18:01
  • 3
    `execfile` worked :D – endolith Sep 22 '15 at 02:08
  • 1
    #1 solved my problem and it was SUPER easy! Thank you! – Rhyuk Sep 30 '16 at 17:40
  • 14
    I was interested in how to define arguments to the other .py script using "import()" – macetw Jan 18 '17 at 18:56
  • What if the file is in a subdirectory? What if it has a .py extension? What if the filename has command-operators in it, like "-" ?How should the "import" line look? How should the function-call look? – macetw Jan 18 '17 at 19:19
  • 3
    Assuming you know what modules are and modules aren't what you want here, `execfile` is the right answer. I see no reason why it's any less secure than importing. You may also want to look at `compile`. – namey Jun 01 '17 at 14:16
  • 2
    best first is ordre of preference, or of inverted preference? – kouty Jun 01 '17 at 19:25
  • If you need to call a "main" function, case #1 is not so obvious. See https://stackoverflow.com/a/14500330/3244382 and https://stackoverflow.com/a/20158605/3244382 – PatriceG Jul 03 '17 at 09:15
  • Can you give reasons why `execfile` is supposed to be less secure than `import`? – timgeb Jul 02 '18 at 08:02
  • unc paths can be used with easily with `execfile(...)` you'll just want to use make sure to use forward slashes instead of backslashes. `execfile('//unc_network_folder/myUNCpythonscript.py')` – hewstone Nov 20 '18 at 14:30
  • The number one just did not work and gave me invalid syntax – FabioSpaghetti Mar 23 '19 at 16:59
  • number 2 doesn't work and says doesn't know exefile – FabioSpaghetti Mar 23 '19 at 16:59
  • Number 3 opens the py file in notepad editor – FabioSpaghetti Mar 23 '19 at 17:00
  • Are you able to provide more detail on the first solution "Treat it like a module"? I tried this but am getting a Syntax error when I use "Import File" and the file name. – wolfblitza Nov 25 '19 at 16:52
  • Don't think you can do option 1 anymore with Python 3, main() is not always available, like in this case: `AttributeError: module 'sqlacodegen' has no attribute 'main'` – NaturalBornCamper Apr 25 '20 at 04:26
  • For ```exec(open('file.py').read())``` how can I pass parameter? – Bogota May 14 '20 at 06:56
  • ~Not sure if I like this as an answer as my python file is in a different directory, and I'm using a piece of structured commerical simulation software running IronPython. How does import #### work when the path is different? – CromeX Jul 06 '21 at 15:12
  • If you are getting a syntax error, it might be because you are using special characters in the name of the file your are trying to import. For me, the error disappeared when I got rid of all `-` and `_` in the file name and only used letters. – Matthias Reccius Oct 15 '21 at 09:57
  • Will suggestion #1 execute the files asynchronously, meaning, if I do `import file1` and `import file2` will `file2.py` execute once `file1.py` is finished running or will they run at the same time? – Freddy Jan 26 '23 at 18:23
80

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?

Jonathan
  • 6,741
  • 7
  • 52
  • 69
Eric Leschinski
  • 146,994
  • 96
  • 417
  • 335
49

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

from subprocess import call
call(["python", "your_file.py"])
Samat Sadvakasov
  • 639
  • 5
  • 10
33
  • 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.

Ayser
  • 1,035
  • 12
  • 15
18
from subprocess import Popen

Popen('python filename.py')

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

Bhargav Rao
  • 50,140
  • 28
  • 121
  • 140
Axel Der
  • 421
  • 3
  • 10
  • 3
    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. – Chandral Sep 15 '20 at 04:52
  • 1
    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? – Jason Oct 03 '20 at 23:01
  • 2
    on python3 i needed to use `Popen(['python3', 'filename.py'])` – ALM Sep 29 '21 at 12:17
  • I get `OSError: [WinError 193] %1 is not a valid Win32 application` with this solution. See https://stackoverflow.com/questions/25651990/oserror-winerror-193-1-is-not-a-valid-win32-application – Theo F Jan 05 '23 at 15:38
6

You could use this script:

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

Syntax:

run("file.py")
xcrafter_40
  • 107
  • 1
  • 10
  • 2
    What's the logic behind this? – Enkouyami Jul 11 '18 at 15:11
  • 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](https://docs.python.org/2.0/ref/exec.html) – xcrafter_40 Jan 26 '19 at 22:56
  • But what is the logic of doing it in this way instead of simply `exec("file.py")` per [this answer](https://stackoverflow.com/a/7975511/1227469)? – JBentley Feb 05 '20 at 15:24
  • 1
    You probably mean execfile("file.py"), and it isn't supported as of Python 3. – Mike Battaglia Sep 12 '21 at 00:20
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

Adam Zalcman
  • 26,643
  • 4
  • 71
  • 92
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'
Lioness100
  • 8,260
  • 6
  • 18
  • 49
Alphard
  • 25
  • 3