我有两个Python文件,文件1和文件2,它们分别做两件事。我想一起运行它们。我正在使用VS2017
文件1的伪代码是:
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();
目前,当我使用这种格式时,子进程会启动文件2并运行它,但if-else条件之后的foo2()的其余代码仅在进程终止时运行(我在文件2中设置的另一个条件) )。
我试图以这样的方式工作,一旦满足if-else条件,文件2将在后台开始运行,并且将在命令窗口中给出输出但是也运行文件1的其余部分。不暂停运行文件1直到file2完成。如果没有在子进程中有另一种方法同时启动两个文件,但通过传递“变量”的值来控制文件2的输出。我想找个合适的解决方法。
我是Python的新手。
编辑1:
我使用了命令:
process = subprocess.Popen('py file2.py' ,shell=True,stdin=None, stdout=None, stderr=None, close_fds=True)
即使我使用process.kill(),子进程仍然在后台运行。即使使用任务管理器也不会退出。
我还想将变量传递给第二个文件。我正在研究类似的东西
variable = input("enter variable)
subprocess.Popen('py file2.py -a' + variable ,shell=True,stdin=None, stdout=None, stderr=None, close_fds=True)
但据我所知,有人告诉我只能通过子进程传递字符串。这是真的吗?
我相信你可以用多线程和多处理来做到这一点。如果要立即启动它们然后监视变量,可以使用管道或队列连接它们。
触发时开始:
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();
马上开始:
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);