使用python的flask框架同步两台机器的剪切板,目前之支持文本的同步。
代码
ubuntu中的python代码
from flask import Flask, request
import pyperclip
import json
import threading
import time
import requests
import logging
TEXT = pyperclip.paste()
app = Flask(__name__)
@app.route('/shearplate', methods=['GET', 'POST'])
def shear_plate():
global TEXT
if request.method == 'POST':
dd = request.data
dd = json.loads(dd.decode())
# dd = request.form
logging.info(f"{dd}, {type(dd)}")
text = dd.get("text", "")
TEXT = text
pyperclip.copy(text)
return text
else:
return "error"
def check_shear_plate():
global TEXT
while True:
time.sleep(1)
text = pyperclip.paste()
if text and TEXT and TEXT != text:
logging.info(f"send data: {text}")
TEXT = text
try:
response = requests.post("http://192.168.0.167:8077/shearplate", data = json.dumps({"text":text}))
logging.info(f"return data: {response.text}")
except:
logging.info("send error...")
if __name__ == '__main__':
t1 = threading.Thread(target=check_shear_plate)
t1.setDaemon(bool)
t1.start()
app.run(host="0.0.0.0", port=8077, debug=False)
windows10中的python代码
from flask import Flask, render_template_string, request
from flask import url_for
import pyperclip
import json
import threading
import time
import requests
import logging
TEXT = pyperclip.paste()
app = Flask(__name__)
@app.route('/shearplate', methods=['GET', 'POST'])
def shear_plate():
global TEXT
if request.method == 'POST':
dd = request.data
dd = json.loads(dd.decode())
# dd = request.form
logging.info(f"{dd}, {type(dd)}")
text = dd.get("text", "")
TEXT = text
pyperclip.copy(text)
return text
else:
return "error"
def check_shear_plate():
global TEXT
while True:
time.sleep(1)
text = pyperclip.paste()
if text and TEXT and TEXT != text:
logging.info(f"send data: {text}")
TEXT = text
try:
response = requests.post("http://192.168.0.124:8077/shearplate", data = json.dumps({"text":text}))
logging.info(f"return data: {response.text}")
except:
logging.info("send error...")
if __name__ == '__main__':
t1 = threading.Thread(target=check_shear_plate)
t1.setDaemon(bool)
t1.start()
app.run(host="0.0.0.0", port=8077, debug=False)
设置开机启动
ubuntu设置开机启动
在终端输入如下命令,打开“启动应用程序首选项”
gnome-session-properties
先点击“添加”,再输入脚本启动命令,最后点击“保存”。
windows下flask设置开机启动
因为需要开机启动,又需要隐藏终端所以比较麻烦,尝试了很多方法都没有成功。最终方案用Nuitka打包python脚本为exe,再将exe的快捷方式放入启动目录。
先安装Nuitka
pip install Nuitka
再打包为exe
nuitka --windows-disable-console 脚本名.py