让Python脚本在后台监听
我制作了一个非常简单的python脚本,可以在ip+端口上侦听。我有一个网络条形码扫描仪,它在ip+端口组合上发送orderID,这个脚本将从api获取标签,并将其发送到打印机。这是工作,因为它应该,我运行它的树莓 我唯一的问题是,每当我想将其作为服务运行以持续运行并侦听ip以进行新扫描时,它只侦听第一次扫描并打印正确的标签,但第二次扫描得到相同的标签让Python脚本在后台监听,python,linux,ubuntu,Python,Linux,Ubuntu,我制作了一个非常简单的python脚本,可以在ip+端口上侦听。我有一个网络条形码扫描仪,它在ip+端口组合上发送orderID,这个脚本将从api获取标签,并将其发送到打印机。这是工作,因为它应该,我运行它的树莓 我唯一的问题是,每当我想将其作为服务运行以持续运行并侦听ip以进行新扫描时,它只侦听第一次扫描并打印正确的标签,但第二次扫描得到相同的标签 import socket import urllib.request import cups import base64 import jso
import socket
import urllib.request
import cups
import base64
import json
import re
from PIL import Image
PrintConn = cups.Connection()
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
s.connect(('192.168.18.208', 51235))
while 1:
contin = False
data = s.recv(512)
print(data)
if not data: break
if not data == b'\x02\x18\r\n':
contin = True
barCode = re.findall(r'\d+', data.decode("utf-8"))
print("https://example.com/api/upsgif/{}".format(''.join(map(str, barCode))))
if contin:
try:
url = "https://example.com/api/upsgif/{}".format(''.join(map(str, barCode)))
req = urllib.request.Request(url, headers={'User-Agent' : "Magic Browser"})
response = urllib.request.urlopen(req).read().decode('utf-8')
if not response: break
upsGif = bytes(response, 'utf-8')
if not upsGif: break
if upsGif == b'\n': break
except urllib.error.HTTPError:
print('Error while getting order label')
else:
with open("label.png", "wb") as fh:
fh.write(base64.decodebytes(upsGif))
img = Image.open('label.png')
PrintConn.printFile('Zebra_Printer', '/var/www/label.png', "",{'fit-to-page':'True'})
这就是我所做的服务:
[Unit]
Description=Autoinpak keepalive daemon
## make sure we only start the service after network is up
Wants=network-online.target
After=network.target
[Service]
## use 'Type=forking' if the service backgrounds itself
## other values are Type=simple (default) and Type=oneshot
Type=forking
## here we can set custom environment variables
ExecStart=/var/www/runClient.sh
ExecStop=/usr/bin/killall -9 autoinpak
Restart=always
TimeoutSec=infinity
# Useful during debugging; remove it once the service is working
StandardOutput=console
[Install]
WantedBy=multi-user.target
还有bash脚本:
#!/bin/bash
while true; do
sudo python3 /var/www/client.py &>/var/log/python/client.log
wait $!
sleep 10
done
exit
我所期望的是,它的工作原理与从终端(python3/var/www/client.py)运行脚本时相同但是,它始终使用相同的upsgif,因此每次标签打印都与我第一次扫描相同。我强烈建议使用
supervisord
而不是这种systemd
方法,并使用requests
而不是urllib