![](/img/trans.png)
[英]Python raw_input & Bazel: EOFError: EOF when reading a line
[英]python loop(): raw_input() EOFError: EOF when reading a line
這是腳本(/shutdown.py)。 它監視按鈕的按下,如果按下按鈕的時間超過3秒鍾,它將運行poweroff命令。
#!/usr/bin/python
# Import the modules to send commands to the system and access GPIO pins
from subprocess import call
from time import sleep
import RPi.GPIO as gpio
import time
# Define a function to keep script running
def loop():
raw_input()
# Define a function to run when an interrupt is called
def shutdown(pin):
button_press_timer = 0
while True:
if (gpio.input(17) == False) : # while button is still pressed down
button_press_timer += 1 # keep counting until button is released
if button_press_timer == 3:
#print "powering off"
call('poweroff', shell=True)
sleep(1)
else: # button is released, figure out for how long
#print "Poga atlaista. nospiesta bija " + str(button_press_timer) + " sekundes"
#button_press_timer = 0
return
# sleep(1) # 1 sec delay so we can count seconds
# print "powering off"
gpio.setmode(gpio.BCM) # Use BCM GPIO numbers
gpio.setup(17, gpio.IN, pull_up_down=gpio.PUD_UP) # Set up GPIO 17 as an input
gpio.add_event_detect(17, gpio.FALLING, callback=shutdown, bouncetime=200) # Set up an interrupt to look for button presses
loop() # Run the loop function to keep script running
如果我從/shutdown.py
控制台運行腳本,一切都很好。 檢測到按下按鈕,並啟動系統關閉程序。 但是,如果我將該腳本添加到/etc/rc.local
),則啟動時會失敗,並顯示以下錯誤:
Traceback (most recent call last):
File "/shutdown.py", line 35, in <module>
loop() # Run the loop function to keep script running
File "/shutdown.py", line 11, in loop
raw_input()
EOFError: EOF when reading a line
如果我注釋掉loop()
行,則沒有錯誤,並且腳本不在后台運行。 我只是啟動和退出,未檢測到按鈕按下。 那么,我如何在啟動時運行該腳本並保持在后台運行?
編輯
我不是python專家,我認為loop()
是python內部函數。 現在我看到它是定義的函數,它調用raw_input()
。 我找到並修改了該腳本以適合我的需求。 謝謝。
您真正需要的是在后台運行的Python守護程序。 您嘗試使用的raw_input方法對我來說似乎是一個丑陋的hack。
看一下python-daemon軟件包,它完全適合您的用例,並且使用起來非常簡單。 還有一個更新的fork支持Python 3。
安裝python-daemon之后,將此行添加到腳本的開頭
import daemon
然后用以下代碼替換腳本末尾的loop()調用:
with daemon.DaemonContext():
while True:
time.sleep(10)
這段代碼未經測試,但是您可以理解。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.