Run a process and kill it if it doesn't end within one hour

前端 未结 5 898
猫巷女王i
猫巷女王i 2020-12-05 00:51

I need to do the following in Python. I want to spawn a process (subprocess module?), and:

  • if the process ends normally, to continue exactly from the moment it
5条回答
  •  执念已碎
    2020-12-05 01:42

    Koodos to Peter Shinners for his nice suggestion about subprocess module. I was using exec() before and did not have any control on running time and especially terminating it. My simplest template for this kind of task is the following and I am just using the timeout parameter of subprocess.run() function to monitor the running time. Of course you can get standard out and error as well if needed:

    from subprocess import run, TimeoutExpired, CalledProcessError
    
    for file in fls:
        try:
            run(["python3.7", file], check=True, timeout=7200)  # 2 hours timeout
            print("scraped :)", file)
        except TimeoutExpired:
            message = "Timeout :( !!!"
            print(message, file)
            f.write("{message} {file}\n".format(file=file, message=message))
        except CalledProcessError:
            message = "SOMETHING HAPPENED :( !!!, CHECK"
            print(message, file)
            f.write("{message} {file}\n".format(file=file, message=message))
    
    

提交回复
热议问题