我制作了一个非常简单的python脚本,可以监听ip +端口。我有一个网络条形码扫描仪,该扫描仪在该ip +端口组合上发送一个orderID,此脚本将从api中获取标签,然后将其发送到打印机。这可以正常工作,我在覆盆子上运行它。
我唯一的问题是,每当我想将其作为服务运行以不断运行并侦听ip进行新扫描时,它仅侦听第一次扫描并打印正确的标签,而第二次扫描获得相同的标签。 / p>
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,因此每个标签打印都与我进行的第一次扫描。