How to call Python File from Another Python File?
Last updated:18th Feb 2022
There are multiple ways you can run Python File from Another Python File. for example, you have two python files 'first.py' and 'second.py', you want to execute the second.py python program inside your first.py program.
1) Run a Python script from another Python using a subprocess
first.py
import subprocess
print("it is first python file")
subprocess.Popen('python second.py')
print("hello")
second.py
print("currently executing the second python file")
a=5
b=10
c=a+b
print("inside the second file output of program is ",c)
when you run the first.py python file your output will be
output
currently executing the first python file hello currently executing the second python file inside the second file output of program is 15
first, you need to import the subprocess, subprocess is a python module used to create a new process for running another program.
subprocess.Popen('python second.py'), it will run your 'second.py' python file
2) use call method of subprocess
import subprocess
print("it is first python file")
subprocess.call('python second.py')
print("hello")
output
currently executing the second python file inside the second file output of program is 15 hello
3) Python program to execute another program using execfile() or exec()
#for python 2
execfile('second.py')
#for python 3
exec(open("second.py").read())
it will run the second file
4) it will stop the execution of a current program and start executing a second program
import os
os.system('python second.py')
print("hello")