首页 > 解决方案 > 如何在批处理文件上停止 python 脚本

问题描述

我想启动一个 python 脚本,然后在 2 分钟后自动关闭该脚本,运行另一个命令,然后像这样(循环)永远继续做同样的事情:

Cd c:/location.of.script/
pythonscript.py
Stop (like ctrl+c) pythonscript.py after 120s
Del -f cookies.file
.
.
. 

这甚至可以在 Windows 10 上使用批处理文件吗?如果是这样,有人可以帮我解决这个问题吗?

我一直在到处寻找,但除了exit()从内部停止脚本的命令外什么也没找到——这不是我想做的。

标签: pythonbatch-filecmd

解决方案


您可以将 python 脚本更改为在 2 分钟后退出,您可以批处理文件,该文件有一个永远运行的 while 循环并运行 python 脚本,然后删除 cookie.file,我不知道这是否正是您想要的,但是你可以通过在你的python脚本中放置一个计时器来做到这一点。

您可以创建一个单独的线程来跟踪时间并在一段时间后终止代码。

此类代码的示例可能是:

import threading

def eternity(): # your method goes here
    while True:
        pass

t=threading.Thread(target=eternity) # create a thread running your function
t.start()                           # let it run using start (not run!)
t.join(3)                           # join it, with your timeout in seconds

这段代码是从https://stackoverflow.com/a/30186772/4561068复制的


推荐阅读