1

I have two Python files, file 1 and file 2 that does two separate things. I want to run them together. I am using VS2017

The pseudo code for file 1 is:

Class A:
   foo1():
    .
    .
   foo2();
    if variable<30;
        #do this
    else;
      subprocess.Popen('py file2.py')

    #rest of the code for foo2()

if __name__ == "__main__":   
  A.foo2();

Currently when I use this format, the subprocess does start the file 2 and run it but the rest of the code for foo2() after the if-else condition runs only when the process is terminated( another condition that I have setup inside file 2).

I am trying to work it in such a way that, file 2 will start running in the background once the if-else condition is met, and will give outputs in the command window but also run the rest of file 1. Not pausing the running of file 1 till file2 is done. If not in subprocess is there another way to start both files simultaneous but control the output of file 2 by passing the value of the "variable". I am trying to figure a proper work-around.

I am new to Python.

EDIT 1:

I used the command:

process = subprocess.Popen('py file2.py' ,shell=True,stdin=None, stdout=None, stderr=None, close_fds=True)

Even if I use process.kill(), the subprocess still runs in the background. It won't quit even if use the task manager.

I also wanted to pass a variable to the second file. I am looking into something like

variable = input("enter variable)
subprocess.Popen('py file2.py -a' + variable ,shell=True,stdin=None, stdout=None, stderr=None, close_fds=True)

But as far as I have looked, it was told that I can only pass strings through a subprocess. is it true?

Abhishek V. Pai
  • 241
  • 1
  • 10
  • 27
  • Possible duplicate: [Run process and don't wait](https://stackoverflow.com/questions/3516007/run-process-and-dont-wait) – zan Mar 08 '19 at 22:03
  • https://docs.python.org/3/library/concurrent.futures.html – solbs Mar 08 '19 at 22:24

1 Answers1

0

I believe you can do this with both multithreading and multiprocessing. If you want to start them both right away and then monitor the variable, you can connect them with a pipe or queue.

starting when triggered:

from py_file2.py import your_func
import threading

Class A:
   foo1():
    .
    .
   foo2();
    if variable<30;
         #do this
    else;

      #put something here to make sure it only starts once
      t = threading.Thread(target = your_func)
      t.start()

    #rest of the code for foo2()

if __name__ == "__main__":   
  A.foo2();

starting right away:

from py_file2.py import your_func
import threading
from queue import Queue

Class A:
   foo1():
    .
    .
   foo2(your_queue);
    if variable<30;
         #do this
    else;

      your_queue.put(variable)

    #rest of the code for foo2()

if __name__ == "__main__": 
  your_queue = Queue()
  t = threading.Thread(target = your_func, args = (your_queue,))
  t.start()  
  A.foo2(your_queue);
JCollinski
  • 54
  • 1
  • 6