【问题标题】:Invoking and using Linux find correctly with a database in python使用python中的数据库正确调用和使用Linux find
【发布时间】:2015-07-07 21:37:56
【问题描述】:

我问了一个类似的问题,但忽略了数据库部分:

Implementation of the Linux find command in python

大多数这些答案的问题是subprocess 方法确实正确实现了查找,但只能在我的计算机中搜索。我正在尝试在 ftp 数据库中进行搜索,并尝试了以下类型的事情:

find_output = subprocess.check_output('find ~', shell = True) 

进入

find_output = subprocess.check_output('find ' + sitename, shell = True)

或

find_output = subprocess.check_output('find ' + sitename, filename, shell = True)

在其他尝试中,但到目前为止没有任何效果。我正在尝试在 ftp 数据库的目录和子目录中搜索特定文件或目录并打印出路径。是否有不是subprocess 的有用方法,或者有没有办法正确调整subprocess 以接受附加参数(站点名、文件名)?

【问题讨论】:

  • 什么是“ftp 数据库”?
  • 我已使用 ftp(文件传输协议)(ftplib) 连接到数据库。不过我没有管理员权限。
  • 但是 ftp 不是数据库。这是一种在计算机之间传输文件的方法。
  • 对不起,我的意思是我可以使用 python 脚本访问数据库并且可以查看它,所以基本上我可以访问文件。

标签: python linux ftp find


【解决方案1】:

尝试使用命令元素列表

>>> subprocess.check_output(["find", ".", "-name", "*.py"])
b'./docs/conf.py\n./setup.py\n'

>>> help(subprocess.check_output)
Help on function check_output in module subprocess:

check_output(*popenargs, timeout=None, **kwargs)
    Run command with arguments and return its output.
...

重新阅读您的问题,您将希望使用 ftp 客户端连接到 ftp 服务器并查看那里的文件。

查看 Python 3 ftplib docs

>>> from ftplib import FTP
>>> with FTP("ftp1.at.proftpd.org") as ftp:
...     ftp.login()
...     ftp.dir()
...

【讨论】:

  • 我很抱歉,但我不太明白最终参数是什么以及这些参数是什么: (*popenargs, timeout=None, **kwargs) 是什么意思。你能解释一下吗?
  • *popenargs 表示它需要一个参数列表。 check_output 调用 subprocess.Popen 所以它将 popen args 传递给它。请参阅上面传递参数列表的帮助示例。重新阅读您的问题后,您可能希望使用 Python 的 ftplib 建立 FTP 连接并使用它来查找您的文件。
【解决方案2】:

我认为你有几个问题需要解决:

1) 正如您所指出的,在 linux 上找到运行它的机器的本地执行。 2) 你试图访问远程 FTP 文件系统(我猜)。

如果您的远程系统是 linux,并且您想使用 find 浏览其文件系统,则您需要远程连接到该计算机。 SSH 可能是一个很好的例子。我刚刚修改了你原来问题的答案。

found = subprocess.Popen(['ssh', 'user@host', 'YOUR FIND CMD'],stdout=subprocess.PIPE)
for line in iter(found.stdout.readline, ''):
   print line,

【讨论】:

  • 如果可能,您能否为正在搜索的文件添加一个参数?或者如果不需要,您能解释一下原因吗?
  • 这取决于你对 find 的实现(我提到你的 FIND CMD),例如使用' find / -name "foo.txt" '会在你的系统中搜索任何名为 foo.txt 的文件.
  • 如果使用 ftp 服务器,主机是 ftp 站点的 url、IP 地址还是其他?
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2020-01-27
  • 2014-06-04
  • 1970-01-01
  • 2019-09-06
  • 1970-01-01
  • 2015-11-29
相关资源
最近更新 更多