我在MacOs Sierra上使用python2.7.10并使用我的raspberrypi在ssh连接上创建了一个rsync。想法是将我的本地文件夹与raspberrypi上的远程文件夹同步。
我的函数syncroFolder()运行正常,但如何在tkinter窗口中显示实时状态?有什么简单的解决方案吗?我无法理解发布的问题:“将命令行结果重定向到tkinter GUI”
def syncroFolder():
os.system("rsync -avz -e \"ssh -p port\" /source/path /folder/to/rcync ")
感谢您的帮助
2017年9月5日: 我设法将结果写在一个带有“| tee”的文件中,我的命令现在看起来像这样
os.system("rsync -avzr -P --info=progress2 -e \"ssh -p %s\" %s %s | tee %s & " %(port,dossier,destination,exampleOutputTxtAdd))
我在TKinter中创建了一个文本框,显示文件的最后一行
status, lastLineInFile = commands.getstatusoutput("tail -n 1 "+ exampleOutputTxtAdd)
T.insert(END,'Transfering: \n'+lastLineInFile)
输出文件如下所示:
sending incremental file list
folder/
0 0% 0.00kB/s 0:00:00 (xfr#0, to-chk=397/410)
folder/Bigfile.avi
32,768 0% 0.00kB/s 0:00:00
2,555,904 0% 2.39MB/s 0:07:18
3,112,960 0% 1.41MB/s 0:12:23
3,637,248 0% 1.11MB/s 0:15:44
但文本框显示所有这些行
Transfering
3,776 0% 0.00kB/s 0:00:00
16,567,040 1% 13.69MB/s 0:01:15
并继续添加行,即使我读取输出文件的-n = 1行。
我一直在尝试使用--out-format = \“%t%o%f%b \”,但之后我只有转移后的状态(如果是大文件)...我尝试了很多选项,没有一个对我有用...我不明白为什么它不显示输出文件的最后一行。 你有什么建议吗?
答案 0 :(得分:0)
这是一个使用python3的例子(因为这就是我所拥有的)。本质如参考示例中所示,使用线程逐行读取管道,然后使用after事件读取队列。增强功能是每次从队列中读取所有项目,并在子进程停止后停止事件后序列。使用python3 tkinter_rsync.py rsync://servername/sharename
或类似的东西进行测试。
import sys
import tkinter as tk
import tkinter.ttk as ttk
from subprocess import Popen, PIPE
from threading import Thread
from queue import Queue, Empty
def read_pipe(widget, queue):
interval = 1
try:
line = queue.get_nowait()
except Empty:
interval = 5
pass
else:
widget.insert('end', line)
widget.after(interval, lambda: read_pipe(widget, queue))
def queue_line(pipe, queue):
for line in iter(pipe.readline, b''):
queue.put(line)
pipe.close()
def main(argv):
root = tk.Tk()
text = tk.Text(root)
vs = ttk.Scrollbar(root, orient='vertical', command=text.yview)
text.configure(yscrollcommand=vs.set)
text.grid(row=0, column=0, sticky='news')
vs.grid(row=0, column=1, sticky='ns')
root.grid_rowconfigure(0, weight=1)
root.grid_columnconfigure(0, weight=1)
process = Popen(['rsync', '--list-only', argv[1]], stdout=PIPE)
queue = Queue()
tid = Thread(target=queue_line, args=(process.stdout, queue))
tid.daemon = True
tid.start()
root.after(0, lambda: read_pipe(text, queue))
root.mainloop()
if __name__ == '__main__':
main(sys.argv)