gpt4 book ai didi

linux - 获取 lsof 命令 Python 3.5 的输出

转载 作者:太空宇宙 更新时间:2023-11-04 12:03:09 29 4
gpt4 key购买 nike

我正在尝试编写一个脚本来监听等待新文件的目录,然后发送到 Nextcloud。这些文件可能很大,所以我想在发送前检查它们是否完整。我考虑过使用 lsof +D path/to/directory 并检查文件是否在命令的输出中,并在文件不在时发送它们。代码将类似于:

command=list()
command.append("lsof")
command.append("+D")
command.append("/path/to/dir")
lsof = subprocess.check_output(command, stderr = subprocess.STDOUT)

但是我得到 subprocess.CalledProcessError 返回非零退出状态 1

有人可以帮助执行命令并将输出放入变量吗?

编辑:

Traceback (most recent call last):
File "<stdin>", line 1, in <module>
File "/usr/lib/python3.5/subprocess.py", line 626, in check_output
**kwargs).stdout
File "/usr/lib/python3.5/subprocess.py", line 708, in run
output=stdout, stderr=stderr)
subprocess.CalledProcessError: Command '['lsof', '+D', '/home/CLI2Cache/sync']' returned non-zero exit status 1

最佳答案

对此有几种解决方法。您可以在 check_output -

中使用 shell=True
lsof = subprocess.check_output(command, shell=True, stderr = subprocess.STDOUT)

请注意 shell=True 并不安全,因为它还允许访问许多 shell 命令,如果命令是用户指定的或未正确清理,可能会导致一些漏洞。请通过this了解风险。

更好的方法是使用 subprocess.Popen -

lsof = subprocess.Popen(command, stdout = subprocess.PIPE, stderr = subprocess.PIPE)
try:
output, errs = lsof.communicate(timeout=20)
except TimeoutExpired:
lsof.kill()
output, errs = proc.communicate()

communicate 也很有用,如果您想将输入发送到生成的进程并在每一步获得相应的输出。

关于linux - 获取 lsof 命令 Python 3.5 的输出,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51658981/

29 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com