Python中断不能与os.system一起工作(';清除';)
我在Raspberry Pi上运行了一个python脚本,它使用一个按钮,python会中断。我在使用os.system(“清除”)时遇到了问题。每当我将其包含在代码中时,中断就会停止工作。下面是一个示例,显示了按钮按下4次,然后在使用os.system(“清除”)时停止。知道为什么吗Python中断不能与os.system一起工作(';清除';),python,raspberry-pi,interrupt,Python,Raspberry Pi,Interrupt,我在Raspberry Pi上运行了一个python脚本,它使用一个按钮,python会中断。我在使用os.system(“清除”)时遇到了问题。每当我将其包含在代码中时,中断就会停止工作。下面是一个示例,显示了按钮按下4次,然后在使用os.system(“清除”)时停止。知道为什么吗 import os import time import sys from datetime import datetime import RPi.GPIO as GPIO prev_time = "" pre
import os
import time
import sys
from datetime import datetime
import RPi.GPIO as GPIO
prev_time = ""
prev_counter = 0
counter = 0
# Setup GPIO, button, and event
GPIO.setmode(GPIO.BCM)
button_pin = 17 # Connect button to pin 17 and gnd
GPIO.setup(button_pin, GPIO.IN, pull_up_down=GPIO.PUD_UP)
GPIO.add_event_detect(button_pin, GPIO.FALLING, bouncetime=250)
while True:
try:
# Display the time every 1 second
if prev_time != str(datetime.now().strftime('%I:%M:%S %p')):
prev_time = str(datetime.now().strftime('%I:%M:%S %p'))
if counter == 5: os.system('clear')
if prev_counter <> counter:
print "Button Pressed"
prev_counter = counter
print "Counter: " + str(counter)
print str(datetime.now().strftime('%I:%M:%S %p'))
# Check for the button press event
if GPIO.event_detected(button_pin):
counter += 1
time.sleep(0.1)
except (KeyboardInterrupt, SystemExit):
os.system('clear')
GPIO.cleanup()
sys.exit(0)
导入操作系统
导入时间
导入系统
从日期时间导入日期时间
将RPi.GPIO导入为GPIO
prev_time=“”
上一个计数器=0
计数器=0
#设置GPIO、按钮和事件
GPIO.setmode(GPIO.BCM)
按钮引脚=17#将按钮连接到引脚17和gnd
GPIO.setup(按钮引脚,GPIO.IN,上拉下=GPIO.PUD上拉)
GPIO.add\u event\u detect(按钮针,GPIO.FALLING,bouncetime=250)
尽管如此:
尝试:
#每1秒显示一次时间
如果上一次str(datetime.now().strftime(“%I:%M:%S%p”):
prev_time=str(datetime.now().strftime(“%I:%M:%S%p”))
如果计数器==5:os.system('clear')
如果上一个计数器:
打印“按下按钮”
上一个计数器=计数器
打印“计数器:+str(计数器)
打印str(datetime.now().strftime(“%I:%M:%S%p”))
#检查按钮按下事件
如果检测到GPIO.event(GPIO.event)(按钮针脚):
计数器+=1
睡眠时间(0.1)
除了(键盘中断、系统退出):
操作系统(“清除”)
GPIO.cleanup()
系统出口(0)
它可以是来自子流程的;甚至复制文件描述符都会干扰事件机制
您无需执行clear
命令来清除屏幕-只需输出ANSI转义码'\033[2J'
:
print '\033[2J'
您在哪里看到使用了
?还有datetime.now().strftime(“%I:%M:%S%p”)
已经是一个字符串,您可以简单地比较datetime对象。您还应该使用subprocess.call(“清除”)
,谢谢,subprocess.call(“清除”)行得通!不用担心,始终使用子进程而不是操作系统。该链接提供了替换操作系统调用的示例。使用!=
而不是
在python3中根本不起作用。