【问题标题】:Subprocess includes problematic quotation marks in Python 3.7+子进程在 Python 3.7+ 中包含有问题的引号
【发布时间】:2020-01-03 20:42:38
【问题描述】:

问题

我在使用 Python3 subprocess 模块时遇到错误。子进程围绕着一些重要的位置参数,我用 unicode 引号给它,这会导致 linux 命令 find 失败。

还有其他人遇到过这个问题吗?我基本上是想弄清楚它是否是我的错误配置,或者我是否应该将其作为子流程团队的问题发布。我确信我可以在我的代码中解决它,但它看起来像是一个应该被压扁的错误。

test.py
import subprocess
p = subprocess.run(['find', '/.snapshots/*/snapshot', '-maxdepth', '0', '-type', 'd' ], capture_output=True, encoding='utf-8')
print(p)
test.py 结果
CompletedProcess(
  args=['find', '/.snapshots/*/snapshot', '-maxdepth', '0', '-type', 'd'], 
  returncode=1,
  stdout='',
  stderr='find: ‘/.snapshots/*/snapshot’: No such file or directory\n'
)

我的看法

在我看来,subprocess 正在强制 find 用 unicode 引号将我的路径字符串括起来,而 bash 只是将这些引号注册为另一个字符,就像 find 命令一样。

预期的命令
user@mine:$ find /.snapshots/*/snapshot/ -maxdepth 0 -type d
/.snapshots/1/snapshot/
/.snapshots/2/snapshot/
/.snapshots/3/snapshot/
命令它似乎正在运行
user@mine:$ find ‘/.snapshots/*/snapshot’ -maxdepth 0 -type d
find: ‘‘/.snapshots/*/snapshot\’’: No such file or directory

引号是 unicode 的事实不是问题。使用 find 命令(至少根据我使用过的版本的经验),您只是不想传递被任何类型的引号包围的路径。即使有一种变通方法使这种行为适用于 find 命令,等待下一个不需要引号的 bash 程序似乎仍然是个问题。

另一个失败的查找命令
user@mine:$ find '/.snapshots/*/snapshot' -maxdepth 0 -type d
find: '/.snapshots/*/snapshot': No such file or directory

系统详情

当我第一次遇到这个问题时,我运行的是 Python 3.7.4。我更新看看是否有修复,所以我现在正在运行 python 3.8.1。我在 Arch Linux 上运行,所以我预计这可能是使用仍在测试中的软件的典型痛苦。

【问题讨论】:

  • 全局和引号是外壳的东西。这里不涉及 shell。
  • 引号不是问题;在find 已经失败后,它们只是错误消息的一部分。问题是 glob 没有被扩展,因为您没有使用 shell 来运行命令,并且 /.snapshots/*/snapshot 是字面意思。

标签: python bash subprocess python-3.7 python-3.8


【解决方案1】:

不要使用 glob(shell 打算在 find 运行之前扩展它),而是使用以下内容:

p = subprocess.run(['find', '/.snapshots/', '-path', '*/snapshot', '-maxdepth', '2', '-type', 'd' ], capture_output=True, encoding='utf-8')

-path 的参数是一个模式,旨在让find 本身对在/.snapshots 下找到的任何文件使用匹配。

【讨论】:

    猜你喜欢
    • 2012-08-31
    • 1970-01-01
    • 2010-09-12
    • 1970-01-01
    • 2013-06-01
    • 1970-01-01
    • 1970-01-01
    • 2013-12-30
    • 2015-10-09
    相关资源
    最近更新 更多