So I know how to write in a file or read a file but how do I RUN another file?
for example in a file I have this:
a = 1
print(a)
How do I run this using another file?
Advertisement
Answer
JavaScript
x
2
1
file_path = "<path_to_your_python_file>"
2
using subprocess
standard lib
JavaScript
1
3
1
import subprocess
2
subprocess.call(["python3", file_path])
3
or using os
standard lib
JavaScript
1
3
1
import os
2
os.system(f"python3 {file_path}")
3
or extract python code
from the file and run it inside your script:
JavaScript
1
6
1
with open(file_path, "r+", encoding="utf-8") as another_file:
2
python_code = another_file.read()
3
4
# running the code inside the file
5
exec(python_code)
6
exec
is a function that runs python strings exactly how python interpreter
runs python files
.
IN ADDITION
if you want to see the output of the python file:
JavaScript
1
10
10
1
import subprocess
2
p = subprocess.Popen(
3
["python3", file_path],
4
stdout=subprocess.PIPE,
5
stderr=subprocess.PIPE
6
)
7
err, output = p.communicate()
8
print(err)
9
print(output)
10
EXTRA
for people who are using python2
:
JavaScript
1
2
1
execfile(file_path)
2