简体   繁体   English

如何停止python程序的一部分运行,而让其余程序定期执行?

[英]How can I stop part of a python program from running, but have the rest execute regularly?

I am trying to terminate a function prematurely but have the rest of my program run normally. 我试图过早地终止功能,但程序的其余部分正常运行。 I am not allowed to change the behavior of the function. 我不允许更改功能的行为。

I have tried placing the function into a process (using the multiprocessing python library) and terminate that process. 我尝试将函数放入进程(使用多处理python库)并终止该进程。 However, I have been getting an error from the signal library. 但是,我从信号库中得到了一个错误。 I believe that this is because the terminate() function does not terminate the child processes of the parent process, but I am not sure. 我相信这是因为Terminate()函数不会终止父进程的子进程,但是我不确定。

Any help on how I can fix this or new approaches would be greatly appreciated. 我如何解决此问题或新方法的任何帮助将不胜感激。

def train(self):
    import reaver as rvr
    env = rvr.envs.SC2Env(map_name='MoveToBeacon')
    agent = rvr.agents.A2C(env.obs_spec(), env.act_spec(), rvr.models.build_fully_conv, rvr.models.SC2MultiPolicy, n_envs=4)
    agent.run(env)


def run(self):
    import multiprocessing
    p = multiprocessing.Process(target=self.train, args=())
    p.start()

    import time
    time.sleep(120)
    p.terminate()
    p.join()
    print("hello) # agent.run(env) shouldn't be running here

run() 跑()

The following is the error message that I receive. 以下是我收到的错误消息。 Ideally, the output would be just be "hello". 理想情况下,输出将只是“ hello”。

Traceback (most recent call last):
  File "signal.py", line 42, in <module>
    trainingHelper.run()
  File "signal.py", line 34, in run
    p.terminate()
  File "/home/user/miniconda3/lib/python3.6/multiprocessing/process.py", line 116, in terminate
    self._popen.terminate()
  File "/home/user/miniconda3/lib/python3.6/multiprocessing/popen_fork.py", line 56, in terminate
    os.kill(self.pid, signal.SIGTERM)
AttributeError: module 'signal' has no attribute 'SIGTERM'

I believe the problem is that you called your file signal.py, try renaming it and your code should work. 我相信问题是您调用了文件signal.py,尝试重命名它,并且代码应该可以工作。 The signal is also a python module which is in conflict. 该信号也是一个有冲突的python模块。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM