gpt4 book ai didi

python - 将标志从 python 脚本传递到另一个脚本

转载 作者:太空宇宙 更新时间:2023-11-03 21:30:18 24 4
gpt4 key购买 nike

您好,如果我在一个脚本中有一个标志,是否可以将实时更改传递给其他脚本?我的意思是,例如我写了这个脚本。我们将其命名为 script1.py它从串行通信中读取数据并将其保存到 .txt文件。当 data我收到的是 '0'我想通过flag sent_jsonscript2 。那么当 script2获取触发器,POST 数据。有什么建议 ?

while True:
try :
a = ser.readline()
timestamped = str(datetime.datetime.now())
suma = timestamped + "\t " + a.decode('utf-8')
f = open("current_data.txt", 'a')
f.write(suma)
if (a.decode().strip() == '0'):
sent_json = True
saveData()
print("New data is saved!")

sent_json = False
except :
print("Unexpected error: ")
break

我还有另一个脚本,我们将其命名为 script2.py ,其中主要是Flask应用程序:

import sqlite3, json
from flask import Flask, render_template, request
from serialNumber_id import serial_number

import sys

app = Flask(__name__)

@app.route("/")

def PostData():
''' Connect to DB, set the temperature to 2 decimal float, POST Data to DB'''

with open("data.json") as dataFile:
data = json.load(dataFile)


for key, value in data.items():
temperature = "{0:.2f}".format(float(value['data']))
date = value['date']
conn = sqlite3.connect('sensordata.db')
cur = conn.cursor()
cur.execute( """INSERT INTO Temperature_data(temperature, currentdat, currenttime, device) VALUES ((?) , (?), time("now"), (?))""", (temperature, date, serial_number))
conn.commit()

open('data.json', 'w').close()

#######
Code something like

while True:
if sent_json :
do something
else:
do something

# if __name__ == "__main__":
# app.run(host='0.0.0.0', port=8181, debug=True)

请注意,我已尝试过 script2

from script1 import sent_json

脚本也位于同一文件夹中。

最佳答案

因此,既然您无论如何都要进行轮询,那么绝对最简单的事情就是写入某种共享资源(例如文件)。因此,script1 向文件写入一些内容(可能是时间戳),而 script2 不断轮询该文件以检查它是否已更改。

让我警告您,如果您想要性能或效率,这就像任何依赖文件系统的解决方案一样,是一个糟糕的解决方案。

关于python - 将标志从 python 脚本传递到另一个脚本,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53562823/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com