Python 如何使用和if对时间窗口进行编码

Python 如何使用和if对时间窗口进行编码,python,Python,我刚刚收到一个时间窗口代码,用于在时间窗口中启动脚本。 如果时间正常,则打印True,如果时间窗口之外,则打印False。 这工作正常 现在在脚本的第二部分中,仅当时间窗口为 True如果pfd.input\u pins[0],则输入。值==1,而不是testprocess:也是True。 但是如果我运行脚本,即使时间窗口不为真,它也会执行它。需要帮忙吗 #!/usr/bin/python import datetime import subprocess from subprocess im

我刚刚收到一个时间窗口代码,用于在时间窗口中启动脚本。 如果时间正常,则打印
True
,如果时间窗口之外,则打印
False
。 这工作正常

现在在脚本的第二部分中,仅当时间窗口为
True
如果pfd.input\u pins[0],则输入
。值==1,而不是testprocess:
也是
True
。 但是如果我运行脚本,即使时间窗口不为真,它也会执行它。需要帮忙吗

#!/usr/bin/python

import datetime
import subprocess
from subprocess import Popen
import pifacedigitalio
from time import sleep
pfd = pifacedigitalio.PiFaceDigital() # creates a PiFace Digital object
testprocess = None
now = datetime.datetime.now()

if ((now.hour >= 14 and now.minute >=00) and (now.hour < 15)) or ((now.hour >=14) and (now.hour < 15)):

    print(True)
else:
    print(False)


if pfd.input_pins[0].value == 1 and not testprocess:
    subprocess.Popen(["/bin/myscriptxy"])
    testprocess = Popen(["/bin/my script"])
    sleep(1)
if pfd.input_pins[0].value == 0:
    if testprocess:
        testprocess.kill()
        testprocess = None
        subprocess.Popen(["/bin/myscriptxy"])
        sleep(1)
#/usr/bin/python
导入日期时间
导入子流程
从子流程导入Popen
导入pifacedigitalio
从时间上导入睡眠
pfd=PiFaceDigital IO.PiFaceDigital()#创建一个PiFace数字对象
testprocess=None
now=datetime.datetime.now()
如果((now.hour>=14和now.minute>=00)和(now.hour<15))或((now.hour>=14)和(now.hour<15)):
打印(真)
其他:
打印(假)
如果pfd.input_引脚[0]。值==1且不是testprocess:
subprocess.Popen([“/bin/myscriptxy]”)
testprocess=Popen([“/bin/my script”])
睡眠(1)
如果pfd.input_引脚[0]。值==0:
如果测试过程:
testprocess.kill()
testprocess=None
subprocess.Popen([“/bin/myscriptxy]”)
睡眠(1)

如果只希望在第一部分中的条件计算为true时执行第二个代码块,则基本上有两种可能性:

  • 或者,将第二个代码块移动到
    if
    块的主体内

    if ((now.hour >= 14 and now.minute >=00) and (now.hour < 15)) or ((now.hour >=14) and (now.hour < 15)):
        if pfd.input_pins[0].value == 1 and not testprocess:
            ...
    
    通过使用比较链接,可以进一步简化为
    14
    
    time_okay = ((now.hour >= 14 and now.minute >=00) and (now.hour < 15)) or ((now.hour >=14) and (now.hour < 15))
    
    if time_okay and pfd.input_pins[0].value == 1 and not testprocess:
        ...
    
    (now.hour >= 14) and (now.hour < 15)