我如何在python中创建一个脚本,在yy天内每xx分钟执行一次,并且在时间到期后关闭fi

2024-10-08 19:25:07 发布

您现在位置:Python中文网/ 问答频道 /正文

我正在尝试创建和编写执行snmp遍历的脚本

import subprocess, shlex,threading, time 
def snmpquery():
  cmd='snmpwalk -v 2c -c public localhost .enterprises.27611.1.4.5.110.24 >> test2.txt\n'
  arg=shlex.split(cmd)
  subprocess.Popen(cmd,shell=True)
  time.sleep(5)
timeout = time.time() + 15   # 15 seconds from now
while timeout < time.time():
 snmpquery()
print('end')

但问题是,经过15秒后,进程继续运行


Tags: import脚本cmdlocalhosttimedeftimeoutpublic
1条回答
网友
1楼 · 发布于 2024-10-08 19:25:07

至于广义解:

import sys
import time

# Shortcut for multi-platform usage
get_timer = time.clock if sys.platform == "win32" else time.time

def schedule_task(task, tick, ttl):
    timeout = get_timer() + ttl
    while get_timer() < timeout:
        task()
        time.sleep(tick)

然后可以将其用作:schedule_task(snmpquery, 5, 15)(只需从函数中删除time.sleep()),但请记住,在任务端(加上循环)还有一个额外的执行偏差,因此在很长一段时间内它不会非常精确

相关问题 更多 >

    热门问题