Answer the question
In order to leave comments, you need to log in
How to run a file with a script from another file with a script running the first file?
Hello. Does anyone know of a way to run a python script that is in file_1.py for example by running another file file_2.py with code to run file_1.py. To clarify, I’ll say that file_1.py contains an infinite loop that writes data to a file, so a simple import is not enough here, since the code in file_2.py must be interpreted further after file_1.py is launched.
Answer the question
In order to leave comments, you need to log in
subprocess or:
import subprocess
cmd = 'python script.py'
p = subprocess.Popen(cmd, stdout=subprocess.PIPE, shell=True)
out, err = p.communicate()
result = out.split('\n')
for lin in result:
if not lin.startswith('#'):
print(lin)
Hey! As I understand it, you need to inject \ import the code after the first script is executed. Import can be called at the end of the script, and even using conditions. Here is an example:
import_rand = False
if import_rand:
import random
print(int(random.randrange(10)))
elif not import_rand:
print(int(random.randrange(10)))
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question