简体   繁体   English

Supervisord - 运行需要与终端交互的python脚本

[英]Supervisord - running a python script that needs to interact with the terminal

I have a python script, which takes a keyboard entry and enters it into a csv file. 我有一个python脚本,它接受键盘输入并将其输入到csv文件中。 There will be a number of Raspberries which perform the same task and I want to look at a management process, to make sure that the Python script is still running. 将会有许多Raspberries执行相同的任务,我想查看一个管理过程,以确保Python脚本仍在运行。

I was looking at Supervisord, which starts my script and I can monitor the script remotely - however when supervisord starts the python script, it stops it interacting with the terminal - so any keyboard entries aren't picked up by the script. 我正在查看Supervisord,它启动我的脚本并且我可以远程监视脚本 - 但是当supervisord启动python脚本时,它会阻止它与终端进行交互 - 因此脚本不会拾取任何键盘条目。 Is there any way to make the python code start but interact with the commandline? 有没有办法让python代码启动但与命令行交互?

PS This is the first bit of coding, so definitely a Noob! PS这是第一个编码,所以绝对是Noob!


Supervisord.conf: Supervisord.conf:


; Sample supervisor config file.
;
; For more information on the config file, please see:
; http://supervisord.org/configuration.html
;
; Notes:
;  - Shell expansion ("~" or "$HOME") is not supported.  Environment
;    variables can be expanded using this syntax: "%(ENV_HOME)s".
;  - Comments must have a leading space: "a=b ;comment" not "a=b;comment".

[unix_http_server]
file=/tmp/supervisor.sock   ; (the path to the socket file)
chmod=0700                 ; socket file mode (default 0700)
;chown=nobody:nogroup       ; socket file uid:gid owner
;username=user              ; (default is no username (open server))
;password=123               ; (default is no password (open server))

[inet_http_server]         ; inet (TCP) server disabled by default
port=*:9001        ; (ip_address:port specifier, *:port for all iface)
username=user              ; (default is no username (open server))
password=pswd               ; (default is no password (open server))

[supervisord]
logfile=/tmp/supervisord.log ; (main log file;default $CWD/supervisord.log)
logfile_maxbytes=50MB        ; (max main logfile bytes b4 rotation;default 50MB)
logfile_backups=10           ; (num of main logfile rotation backups;default 10)
loglevel=info                ; (log level;default info; others: debug,warn,trace)
pidfile=/tmp/supervisord.pid ; (supervisord pidfile;default supervisord.pid)
nodaemon=false               ; (start in foreground if true;default false)
minfds=1024                  ; (min. avail startup file descriptors;default 1024)
minprocs=200                 ; (min. avail process descriptors;default 200)
;umask=022                   ; (process file creation umask;default 022)
user=pi                 ; (default is current user, required if root)
;identifier=supervisor       ; (supervisord identifier, default is 'supervisor')
;directory=/tmp              ; (default is not to cd during start)
;nocleanup=true              ; (don't clean up tempfiles at start;default false)
;childlogdir=/tmp            ; ('AUTO' child log dir, default $TEMP)
;environment=KEY="value"     ; (key value pairs to add to environment)
;strip_ansi=false            ; (strip ansi escape codes in logs; def. false)

; the below section must remain in the config file for RPC
; (supervisorctl/web interface) to work, additional interfaces may be
; added by defining them in separate rpcinterface: sections

[rpcinterface:supervisor]
supervisor.rpcinterface_factory = supervisor.rpcinterface:make_main_rpcinterface

[supervisorctl]
serverurl=unix:///tmp/supervisor.sock ; use a unix:// URL  for a unix socket
;serverurl=http://10.55.0.102:9001 ; use an http:// url to specify an inet socket
username=user             ; should be same as http_username if set
password=pswd                ; should be same as http_password if set
;prompt=mysupervisor         ; cmd line prompt (default "supervisor")
;history_file=~/.sc_history  ; use readline history if available


[program:GIST]
command=/usr/bin/sudo /usr/bin/python /home/pi/Main.py -DFOREGROUND
;command=/home/pi/Main.py
numprocs=1
autostart=true
startsecs=1
startretries=3
autorestart=unexpected
exitcodes=0,2
stopsignal=QUIT
user=User

; The below sample eventlistener section shows all possible
; eventlistener subsection values, create one or more 'real'
; eventlistener: sections to be able to handle event notifications
; sent by supervisor.



; The below sample group section shows all possible group values,
; create one or more 'real' group: sections to create "heterogeneous"
; process groups.

;[group:thegroupname]
;programs=progname1,progname2  ; each refers to 'x' in [program:x] definitions
;priority=999                  ; the relative start priority (default 999)

; The [include] section can just contain the "files" setting.  This
; setting can list multiple files (separated by whitespace or
; newlines).  It can also contain wildcards.  The filenames are
; interpreted as relative to this file.  Included files *cannot*
; include files themselves.

;[include]
;files = relative/directory/*.ini

Python Script: Python脚本:


import sys, select, datetime, select, fcntl, socket, struct, time, os

#t = datetime.datetime.now()
#timenow = time.mktime(t.timetuple())

def getmac(interface):
        try:
                mac = open('/sys/class/net/'+interface+'/address').readline()
        except:
                mac = "00:00:00:00:00:00"
        return mac[0:17]
myMAC = getmac("wlan0")

def get_ip_addr(ifname):
        try:
                s = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
                return socket.inet_ntoa(fcntl.ioctl(
                        s.fileno(),
                        0x8915,  # SIOCGIFADDR
                        struct.pack('256s', ifname[:15])
                    )[20:24])
        except:
                ()

print get_ip_addr('wlan0')
print myMAC


IPAddr = get_ip_addr('wlan0')

while True:
        if os.path.lexists('/home/pi/GistLog.csv'):

                i, o, e, = select.select([sys.stdin], [], [], 3600)
                if (i):
                        id = sys.stdin.readline().strip()
                        if id == "exit":
                                        break
                        t = datetime.datetime.now()
                        timenow = time.mktime(t.timetuple())

                        with open("/home/pi/GistLog.csv", "a") as Log:
                                Log.write (id + "," +str(timenow)+ "," + str(myMAC) + "," + str(IPAddr) + "," + "\n")

                        print"Scan Successful"
                        print t

                else:
                        print"Scan Error"
        else:
                i, o, e, = select.select([sys.stdin], [], [], 3600)
                if (i):
                        id = sys.stdin.readline().strip()
                        if id == "exit":
                                break
                        t = datetime.datetime.now()
                        timenow = time.mktime(t.timetuple())

                        with open("/home/pi/GistLog.csv", "a") as Log:
                                Log.write ("id,rfid,timestamp,MAC,IPAddr,\n" + id + "," +str(timenow)+ "," + str(myMAC) + "," + str(IPAddr) + "," + "\n")
                else:
                        print"Scan Error"

I managed to work it out - I figured out the supervisorctl fg command, which brought the process to the foreground and let me interact with it. 我设法解决了 - 我想出了supervisorctl fg命令,它将进程带到前台并让我与它进行交互。

I also managed to get this to autostart from the /etc/profile so it launches the supervisord process, sleeps 5, then launches the supervisorctl fb command. 我还设法从/ etc / profile中自动启动它,以便启动supervisord进程,睡眠5,然后启动supervisorctl fb命令。

Chris 克里斯

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM