猿问

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()


慕斯709654
浏览 165回答 3
3回答

米脂

如果您需要运行整个过程(甚至是引导代码),您可以使用 shell 脚本来完成。但这不会刷新环境变量。#!/usr/bin/env bashwhile true; do   sleep 10  python script.pydone如果您需要刷新环境变量(由于 RANDOM_OBJECTS,您似乎需要它),请添加eval "$(exec /usr/bin/env -i "${SHELL}" -l -c "export")"到其中。

RISEBY

尝试这个:if __name__ == "__main__":     time.sleep(10)     main()

慕哥6287543

你能做的就是在 10 秒后重新启动整个脚本。应用于您的代码,它看起来像这样:import osimport timeimport jsonimport sysfrom bacpypes.debugging import bacpypes_debugging, ModuleLoggerfrom bacpypes.consolelogging import ConfigArgumentParserfrom bacpypes.core import runfrom bacpypes.primitivedata import Realfrom bacpypes.object import AnalogValueObject, Property, register_object_typefrom bacpypes.errors import ExecutionErrorfrom bacpypes.app import BIPSimpleApplicationfrom bacpypes.local.device import LocalDeviceObject# Read Jsonwith open('ObjectList.json') as json_file:    data = json.load(json_file)    def get_present_value(no):        for a in data['AnalogValues']:            if a['ObjectIdentifier'] == int(no):                return a['PresentValue']        return Noneai_1 = (get_present_value(1))print(ai_1)# some debugging_debug = 0_log = ModuleLogger(globals())# settingsRANDOM_OBJECT_COUNT = int(os.getenv('RANDOM_OBJECT_COUNT', 1))##   RandomValueProperty#class RandomValueProperty(Property):    def __init__(self, identifier):        if _debug: RandomValueProperty._debug("__init__ %r", identifier)        Property.__init__(self, identifier, Real, default=0.0, optional=True, mutable=False)    def ReadProperty(self, obj, arrayIndex=None):        if _debug: RandomValueProperty._debug("ReadProperty %r arrayIndex=%r", obj, arrayIndex)        # access an array        if arrayIndex is not None:            raise ExecutionError(errorClass='property', errorCode='propertyIsNotAnArray')        # return a random value        value = ai_1        if _debug: RandomValueProperty._debug("    - value: %r", value)        return value    def WriteProperty(self, obj, value, arrayIndex=None, priority=None, direct=False):        if _debug: RandomValueProperty._debug("WriteProperty %r %r arrayIndex=%r priority=%r direct=%r", obj, value,                                              arrayIndex, priority, direct)        raise ExecutionError(errorClass='property', errorCode='writeAccessDenied')bacpypes_debugging(RandomValueProperty)##   Random Value Object Type#class RandomAnalogValueObject(AnalogValueObject):    properties = [        RandomValueProperty('presentValue'),    ]    def __init__(self, **kwargs):        if _debug: RandomAnalogValueObject._debug("__init__ %r", kwargs)        AnalogValueObject.__init__(self, **kwargs)bacpypes_debugging(RandomAnalogValueObject)register_object_type(RandomAnalogValueObject)##   __main__#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()    time.sleep(10)    os.execl(sys.executable, sys.executable, * sys.argv)  # Your script restarts after 10s with this
随时随地看视频慕课网APP

相关分类

Python
我要回答