D
D
Danil Samodurov2020-09-09 22:12:52
Python
Danil Samodurov, 2020-09-09 22:12:52

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

2 answer(s)
V
Viktor T2, 2020-09-10
@samodurOFF

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)

https://stackoverflow.com/questions/3781851/run-a-...

K
koval01, 2020-09-09
@koval01

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)))

If True, then the random module is imported and a number will be displayed, if False, then there will be an error (The random module was not found).

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question