我有一个紧急按钮和一个响应按钮按下的脚本。
如果我将进程发送到后台,使用命令$sudo python3 ./Panicbutton.py &
我将获得命令行。当我按下panic按钮时,脚本会做出响应,并打印与按钮按下次数对应的消息。我要它做的是回到后台,同时等待更多的按钮按下。按ctrl+c返回到命令行,但我不想每次按下按钮后都按ctrl+c。有没有办法让脚本在等待下一次按键时返回到后台?如何将ctrl+c命令从脚本发送到终端?我不想终止进程,我只想在消息打印后返回命令行提示符。在
我使用的是Linux和python3.4。请协助。在
脚本如下:
# USB Panic Button interface code
# Copyright 2010 Ken Shirriff
# http://arcfn.com
import usb.core
x = 0
comment0 = """ PanicButton - interface to USB Panic Button This code requires PyUSB."""
class PanicButton:
def __init__(self):
# Device is: ID 1130:0202 Tenx Technology, Inc.
self.dev = usb.core.find(idVendor=0x1130, idProduct=0x0202)
if not self.dev:
raise ValueError("Panic Button not found")
try:
self.dev.detach_kernel_driver(0) # Get rid of hidraw
except Exception as e:
pass # already unregistered
def read(self):
comment1 = """ Read the USB port. Return 1 if pressed and released, 0 otherwise."""
#Magic numbers are from http://search.cpan.org/~bkendi/Device-USB-PanicButton-0.04/lib/Device/USB/PanicButton.pm
return self.dev.ctrl_transfer(bmRequestType=0xA1, bRequest=1, wValue=0x300, data_or_wLength=8, timeout=500)[0]
if __name__ == "__main__":
import time
button = PanicButton()
while 1:
if button.read():
global x
x = x + 1
if x < 5:
print(x)
elif x == 5:
print("Baby just screem if you want some more!")
elif x == 6:
print("Like AH!")
elif x == 7:
print("push it, push it.")
elif x == 8:
print("watch me work it.")
elif x == 9:
print("I'm PERFECT")
else:
x = 0
print("")
time.sleep(.5)
脚本始终在后台,并且在任何时候都不会转到前台。它看起来是那样的,因为脚本的输出具有纯粹的装饰效果,看起来像是把提示搞得一团糟。在
不用按Ctrl-C,只需编写
ls
并按enter键。您将看到shell工作正常,而您的脚本不在前台。在Bash不能真正地重新绘制提示,因为它不控制其他哪些程序写入屏幕。考虑寻找一种侵入性较小的方法来报告按钮按下情况,例如:
bel
字符以使终端播放声音tmux
或{相关问题 更多 >
编程相关推荐