pass arguments through a subprocess and terminate the subprocess when closing the main program in Python in Windows

时间:2019-03-19 15:10:09

标签: python windows error-handling subprocess parameter-passing

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;
      process = subprocess.Popen('py file2.py' ,shell=True,stdin=None, stdout=None, stderr=None, close_fds=True)

    #rest of the code for foo2()

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

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

variable = input("enter variable)
cmd = ['py file2.py', variable]
subprocess.Popen(cmd ,shell=True,stdin=None, stdout=None, stderr=None, close_fds=True)

I am getting an error saying:

'"py subproleap.py"' is not recognized as an internal or external command, operable program or batch file.

And Even if I do pass the variable how do I get the file2.py to read it?

Any help would be appreciated. I am a beginner in python.

EDIT1: Why I use subprocess is that I want the file2.py to run in the background,once the condition is met, while the main process runs in the side.

1 个答案:

答案 0 :(得分:0)

This可能会回答您的问题(您正在使用shell=True参数)

但是将file2作为模块导入file1会更容易吗? (如果您还不熟悉导入,可以参考this guide