我在Ubuntu上用python编写程序。在该程序中,我很难在连接RaspberryPi的远程网络上使用命令askopenfilename
选择文件。
有人可以指导我如何使用askopenfilename
命令或类似命令从远程机器中选择文件吗?
from Tkinter import *
from tkFileDialog import askopenfilename
import paramiko
if __name__ == '__main__':
root = Tk()
client = paramiko.SSHClient()
client.set_missing_host_key_policy(paramiko.AutoAddPolicy())
client.connect('192.168.2.34', username='pi', password='raspberry')
name1= askopenfilename(title = "Select File For Removal", filetypes = [("Video Files","*.h264")])
stdin, stdout, stderr = client.exec_command('ls -l')
for line in stdout:
print '... ' + line.strip('\n')
client.close()
答案 0 :(得分:3)
无法使用tkinter的文件对话框列出(或选择)远程计算机上的文件。您需要使用SSHFS(如问题注释中所述)安装远程计算机的驱动器,或使用自定义tkinter对话框显示远程文件列表(位于stdout
变量中)并让你选择那个。
您可以自己编写一个对话窗口,这是一个快速演示:
from Tkinter import *
def double_clicked(event):
""" This function will be called when a user double-clicks on a list element.
It will print the filename of the selected file. """
file_id = event.widget.curselection() # get an index of the selected element
filename = event.widget.get(file_id[0]) # get the content of the first selected element
print filename
if __name__ == '__main__':
root = Tk()
files = ['file1.h264', 'file2.txt', 'file3.csv']
# create a listbox
listbox = Listbox(root)
listbox.pack()
# fill the listbox with the file list
for file in files:
listbox.insert(END, file)
# make it so when you double-click on the list's element, the double_clicked function runs (see above)
listbox.bind("<Double-Button-1>", double_clicked)
# run the tkinter window
root.mainloop()
没有tkinter
的最简单的解决方案是 - 您可以让用户使用raw_input()
函数键入文件名。
有点像:
filename = raw_input('Enter filename to delete: ')
client.exec_command('rm {0}'.format(filename))
因此用户必须输入要删除的文件名;然后该文件名直接传递给rm
命令。
这不是一个真正安全的方法 - 你绝对应该逃避用户的输入。想象一下,如果用户将'-rf /*'
键入为文件名,该怎么办?没有什么好的,即使你没有作为根连接
但是,当你正在学习并保持脚本给自己时,我想这没关系。