1

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?

1 Answer 1

1
file_path = "<path_to_your_python_file>" 

using subprocess standard lib

import subprocess subprocess.call(["python3", file_path]) 

or using os standard lib

import os os.system(f"python3 {file_path}") 

or extract python code from the file and run it inside your script:

with open(file_path, "r+", encoding="utf-8") as another_file: python_code = another_file.read() # running the code inside the file exec(python_code) 

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:

import subprocess p = subprocess.Popen( ["python3", file_path], stdout=subprocess.PIPE, stderr=subprocess.PIPE ) err, output = p.communicate() print(err) print(output) 

EXTRA

for people who are using python2:

execfile(file_path) 

exec_file documentation

Sign up to request clarification or add additional context in comments.

2 Comments

In python 2 you can also use execfile
Also if I'm not mistaken python interpreter does not compile files. It is an interpreter after all.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.