代码之家  ›  专栏  ›  技术社区  ›  Irfan Ghaffar7

Python中远程计算机的文件选择

  •  2
  • Irfan Ghaffar7  · 技术社区  · 10 年前

    我正在Ubuntu上用python编写一个程序。在该程序中,我正努力使用命令选择文件 askopenfilename 在远程网络上连接RaspberryPi。

    有人能指导我如何使用 askopen文件名 命令或类似的东西?

    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()
    
    1 回复  |  直到 10 年前
        1
  •  4
  •   Igor Hatarist    10 年前

    哈哈,你好!

    无法使用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 /*' 作为文件名。没什么好的,即使你不是根用户。
    但当你在学习并将剧本留给自己时,我想这没什么。