请告诉我。我有两个不同的 Python 脚本文件。第一个文件是 Flask 服务器,第二个文件是 TCP 服务器。 Flask 脚本是主文件。启用此参数后,当从同一脚本启动 Flask 时,应启动第二个 TCP 服务器脚本。但由于 TCP 脚本是无穷无尽的,我无法通过子进程来完成它,或者我不明白如何完成。任务是简单地运行这个脚本,而不是进一步监视它,以便它可以自行工作。该怎么办?
服务器烧瓶
#!/usr/bin/sudo python
import time
from flask import Flask, request, jsonify
from flask_restful import Api, Resource, reqparse
import socket
import os
import json
import requests
import logging
from cysystemd import journal
import subprocess
import threading
app = Flask(__name__)
class LoggingSystem:
def __init__(self):
self.log = logging.getLogger('ITCService')
self.log.addHandler(journal.JournaldLogHandler())
self.log.setLevel(logging.INFO)
def run_online_locks_server():
subprocess.Popen(
['python', 'init.py'], stdout=subprocess.PIPE, stderr=subprocess.PIPE
)
def check_system_conf():
start_data = {
"host_address_ip": '192.168.0.19',
"host_address_port": 8181,
"club_software_login": "skud",
"club_software_pass": "skud1234",
"club_software_url": "192.168.88.70/skud/",
"online_locks_port": 9191,
"online_locks_enable": 1,
"online_locks_conf": {
"women": {
"quantity_locks": 48,
"hosts_ip_address": ["192.168.0.178"],
"hosts_port_address": 5001
},
"man": {
"quantity_locks": 48,
"hosts_ip_address": ["192.168.0.178"],
"hosts_port_address": 5001
},
},
"debug_flag_enable": 0
}
if os.path.isdir('/etc/itclocks'):
if os.path.exists('/etc/itclocks/itclocks.json'):
pass
else:
file = open('/etc/itclocks/itclocks.json', 'w')
json.dump(start_data, file, indent=4, sort_keys=True)
file.close()
else:
os.mkdir('/etc/itclocks')
file = open('/etc/itclocks/itclocks.json', 'w')
json.dump(start_data, file, indent=4, sort_keys=True)
file.close()
return load_config_data()
def load_config_data():
file = open('/etc/itclocks/itclocks.json', 'r')
data = json.load(file)
return data
@app.route("/unlock_all", methods=['GET'])
def open_all_locks():
client.send('unlock_all'.encode('utf-8'))
@app.route("/check_status", methods=['GET'])
def check_status():
print('1')
client.send('check_status'.encode('utf-8'))
run_listen = True
while run_listen:
data = client.recv(512)
if len(data) == 0:
pass
else:
print(data)
run_listen = False
@app.route("/unlock_lock", methods=['POST'])
def open_lock():
data1 = request.get_json()
client.send("unlock_lock".encode('utf-8'))
if __name__ == '__main__':
run_online_locks = True
system_data_conf = check_system_conf()
if system_data_conf["online_locks_enable"] == 1:
for i in range(3):
try:
run_online_locks_server()
time.sleep(3)
client = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
client.connect(('192.168.0.19', 10000))
break
except Exception as error:
print(error)
time.sleep(2)
app.run(threaded=True, debug=True, host=system_data_conf['host_address_ip'],
port=system_data_conf['host_address_port'])
TCP服务器
#!/usr/bin/sudo python
import socket
print('fff')
server_cu = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
server_cu.connect(('192.168.0.178', 5000))
server = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
# server.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
server.bind(('192.168.0.19', 10001))
server.listen()
conn, addr = server.accept()
def ask_state():
cmd = [0x02, 0x0A, 0x00, 0x50, 0x03, 0x5F]
server_cu.send(bytes(cmd))
def process_state(data=None):
print(data)
if data is None:
print("empty packet")
return False
if len(data) != 12:
print("Packet length mismatch")
if data[0] != 0x02 or data[2] != 0x00 or data[3] != 0x65 or data[10] != 0x03:
print("invalid packet")
return False
board_number = data[1]
lock_number = 1
states = []
for byte_num in range(4, 10):
for bit_num in range(0, 8):
state = 1 if data[byte_num] & (1 << bit_num) > 0 else 0
print(f"B:{board_number}, L{lock_number}, S{state}")
states.append([board_number, lock_number, state])
lock_number += 1
return str(states)
def unlock_all():
cmd = [0x02, 0x00, 0x30, 0x51, 0x03, 0x86]
server_cu.send(bytes(cmd))
while True:
print(2)
conn, addr = server.accept()
print(3)
while True:
print(4)
datagram = conn.recv(512)
print(5)
if not datagram:
break
if datagram == b'check_status':
cmd = [0x02, 0x00, 0x00, 0x50, 0x03, 0x55]
ask_state()
states = None
data_recv = 0
while states is None:
print(9)
data_recv = server_cu.recv(512)
print(10)
if len(data_recv) == 12:
print(11)
states = False
print(data_recv)
conn.send(data_recv)
if datagram == b'unlock_all':
print(6)
unlock_all()
if b'unlock_lock' in datagram:
cmd = [0x02, 0x00, 0x30, 0x51, 0x03, 0x86]
server_cu.send(bytes(cmd))
conn.sendall(''.encode('utf-8'))
server.close()
总的来说,我找到了问题的解决方案,我将每个脚本分散到单独的文件夹中(只是为了美观))),创建了第三个脚本,即主脚本,并通过线程首先启动 TCP 服务器,然后烧瓶服务器。一切都很好!
方法一:
使用
subprocess
如果你拿不到
stdout
,stderr
那也不错。subprocess.communicate()
- 阻塞方法,即有什么东西启动了然后冻结了。方法二:使用
threading
方法3:使用
threading
casyncio