如何从后台运行的脚本返回命令行

时间:2015-07-09 17:57:46

标签: python linux command-line process terminal

我有这个应急按钮,以及响应按下按钮的脚本。 如果我使用命令$sudo python3 ./Panicbutton.py &将进程发送到后台,我会返回命令行。当我按下应急按钮时,脚本会响应,并打印与按下按钮次数相对应的消息。我想要它做的是回到后台,同时等待更多按钮按下。按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)

1 个答案:

答案 0 :(得分:1)

脚本始终在后台,并且不会在任何时候前往前台。它只是看起来那样,因为脚本的输出具有纯粹的美化效果,似乎弄乱了提示。

您可以只编写ls并按Enter键,而不是按Ctrl-C。您将看到shell工作正常并且您的脚本不在前台。

Bash无法重新提示提示,因为它无法控制哪些其他程序写入屏幕。考虑找一种较少侵入性的按钮按下方式,例如:

  • 打印bel字符以使终端播放声音
  • 更改xterm的标题
  • 使用tmuxscreen来显示窗口或状态栏消息
  • 使用xmessage或类似方法弹出对话框
  • 每次重绘时,让bash提示包含来自脚本的消息
相关问题