本文目錄一覽:
- 1、python time.sleep 隨機數
- 2、python每隔10秒運行一個指定函數怎麼實現
- 3、python每隔N秒運行指定函數的方法
- 4、我想寫一個python讓其紙上面在隨機時間20秒到100秒之間打印一遍hello,world?
python time.sleep 隨機數
你可以查看一下幫助。比如這樣子
Python 2.7.6 (default, Nov 10 2013, 19:24:18) [MSC v.1500 32 bit (Intel)] on win32
Type “help”, “copyright”, “credits” or “license” for more information.
help(time.sleep)
Help on built-in function sleep in module time:
sleep(…)
sleep(seconds)
Delay execution for a given number of seconds. The argument may be
a floating point number for subsecond precision.
time.sleep(5,30)
Traceback (most recent call last):
File “stdin”, line 1, in module
TypeError: sleep() takes exactly 1 argument (2 given)
從幫助里可以看到。sleep(這裡里允許時間秒)秒可以是浮點數。但是不允許多個參數。
如果想隨機可以使用random
比如
import random,time
time.sleep(random.randint(5,30))
python每隔10秒運行一個指定函數怎麼實現
#腳本裏面直接這樣寫就好了import randomdef R(): print (random.randint(1,1000))for i in range(1,10): R()
python每隔N秒運行指定函數的方法
python每隔N秒運行指定函數的方法
這篇文章主要介紹了python每隔N秒運行指定函數的方法,涉及Python的線程與時間操作技巧,非常具有實用價值,需要的朋友可以參考下
這是一個類似定時器的效果,每隔指定的秒數運行指定的函數,採用線程實現,代碼簡單實用。
代碼如下:import os
import time
def print_ts(message):
print “[%s] %s”%(time.strftime(“%Y-%m-%d %H:%M:%S”, time.localtime()), message)
def run(interval, command):
print_ts(“-“*100)
print_ts(“Command %s”%command)
print_ts(“Starting every %s seconds.”%interval)
print_ts(“-“*100)
while True:
try:
# sleep for the remaining seconds of interval
time_remaining = interval-time.time()%interval
print_ts(“Sleeping until %s (%s seconds)…”%((time.ctime(time.time()+time_remaining)), time_remaining))
time.sleep(time_remaining)
print_ts(“Starting command.”)
# execute the command
status = os.system(command)
print_ts(“-“*100)
print_ts(“Command status = %s.”%status)
except Exception, e:
print e
if __name__==”__main__”:
interval = 5
command = r”ipconfig”
run(interval, command)
希望本文所述對大家的Python程序設計有所幫助。
我想寫一個python讓其紙上面在隨機時間20秒到100秒之間打印一遍hello,world?
import time
import random
while(True): #循環條件,可以自行修改,這裡設置一直運行下去
sleeptime=random.randint(20,100) #在這裡產生20到100之間的隨機整數
time.sleep(sleeptime) ##根據上步產生的時間進行休眠
print(“hello,world”) #輸出hello,world
原創文章,作者:GRDB,如若轉載,請註明出處:https://www.506064.com/zh-hk/n/139863.html