首页 > 解决方案 > 10 秒后重新运行 python 脚本

问题描述

我试图每 10 秒重新运行一次我的 python 脚本。我用 time.sleep 函数尝试了各种方法,但似乎没有任何效果。我尝试了 time.sleep 的不同变体:

 def job()
   # script

if __name__ == '__main__':
    while True:
        job()
        time.sleep(10)

但没有找到正确的地方/方式来实现它。我不想重新运行一个函数,而是完整的代码。

这是我试图重新运行的脚本:

import...

def main():
    # parse the command line arguments
    args = ConfigArgumentParser(description=__doc__).parse_args()

    if _debug: _log.debug("initialization")
    if _debug: _log.debug("    - args: %r", args)

    # make a device object
    this_device = LocalDeviceObject(
        objectName=args.ini.objectname,
        objectIdentifier=('device', int(args.ini.objectidentifier)),
        maxApduLengthAccepted=int(args.ini.maxapdulengthaccepted),
        segmentationSupported=args.ini.segmentationsupported,
        vendorIdentifier=int(args.ini.vendoridentifier),

    )

    # make a sample application
    this_application = BIPSimpleApplication(this_device, args.ini.address)

    # make some random input objects
    for i in range(1, RANDOM_OBJECT_COUNT + 1):
        ravo = RandomAnalogValueObject(
            objectIdentifier=('analogValue', i),
            objectName='Temp%d' % (i,),

        )

        this_application.add_object(ravo)

    # make sure they are all there

    _log.debug("    - object list: %r", this_device.objectList)

    _log.debug("running")

    run()

    _log.debug("fini")


if __name__ == "__main__":
    main()

标签: pythonsleep

解决方案


如果您需要运行整个程序(甚至是引导代码),您可以使用 shell 脚本来完成。

不过,这不会刷新环境变量。

#!/usr/bin/env bash

while true; do 
  sleep 10
  python script.py
done

如果您需要刷新环境变量(由于 RANDOM_OBJECTS,您似乎需要它),添加eval "$(exec /usr/bin/env -i "${SHELL}" -l -c "export")"到组合中。来源:https ://unix.stackexchange.com/a/581684


推荐阅读