python - 在批处理文件中休眠

在编写批处理文件以在 Windows 机器上自动执行某些操作时,我需要暂停其执行几秒钟(通常在测试/等待循环中,等待进程启动)。当时,我能找到的最佳解决方案是使用 ping (我不骗你)来达到预期的效果。我找到了更好的写法here ,它描述了一个可调用的“wait.bat”,实现如下:

@ping 127.0.0.1 -n 2 -w 1000 > nul
@ping 127.0.0.1 -n %1% -w 1000> nul

然后,您可以在自己的批处理文件中包含对 wait.bat 的调用,并传入休眠的秒数。

Apparently the Windows 2003 Resource Kit provides a Unix-like sleep command (最后!)。与此同时,对于我们这些仍在使用 Windows XP、Windows 2000 或(可悲的)Windows NT 的人来说,有没有更好的办法?

我修改了 accepted answer 中的 sleep.py 脚本,因此如果命令行上没有传递任何参数,则默认为一秒:

import time, sys

time.sleep(float(sys.argv[1]) if len(sys.argv) > 1 else 1)

最佳答案

timeout从 Windows Vista 开始可以使用命令:

c:\> timeout /?

TIMEOUT [/T] timeout [/NOBREAK]

Description:
    This utility accepts a timeout parameter to wait for the specified
    time period (in seconds) or until any key is pressed. It also
    accepts a parameter to ignore the key press.

Parameter List:
    /T        timeout       Specifies the number of seconds to wait.
                            Valid range is -1 to 99999 seconds.

    /NOBREAK                Ignore key presses and wait specified time.

    /?                      Displays this help message.

NOTE: A timeout value of -1 means to wait indefinitely for a key press.

Examples:
    TIMEOUT /?
    TIMEOUT /T 10
    TIMEOUT /T 300 /NOBREAK
    TIMEOUT /T -1

注意:它不适用于输入重定向 - 简单示例:

C:\>echo 1 | timeout /t 1 /nobreak
ERROR: Input redirection is not supported, exiting the process immediately.

https://stackoverflow.com/questions/166044/

相关文章:

linux - Shell - 将变量内容写入文件

python - 如何在 Python 中使用方法重载?

python - 在 Python 中 Ping 服务器

python - 为什么这个 Python 代码段中允许使用分号?

python - Anaconda 与 miniconda

unix - 如何交错来自两个文本文件的行

c - 如何使用 GDB 修改内存内容?

python - 如何在 Windows 上使用 Python 3 连接到 MySQL?

linux - Linux内核中浮点的使用

linux - 如何从文本文件中删除非 UTF-8 字符