python - subprocess.check_output() : OSError file not found in Python

标签 python

执行以下命令及其变体总是会导致错误,我无法弄清楚:

command = "/bin/dd if=/dev/sda8 count=100 skip=$(expr 19868431049 / 512)"

print subprocess.check_output([command])

Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
  File "/usr/lib/python2.7/subprocess.py", line 566, in check_output
    process = Popen(stdout=PIPE, *popenargs, **kwargs)
  File "/usr/lib/python2.7/subprocess.py", line 710, in __init__
    errread, errwrite)
  File "/usr/lib/python2.7/subprocess.py", line 1327, in _execute_child
    raise child_exception
OSError: [Errno 2] No such file or directory

它指的是哪个文件?尽管 ls、wc 等其他命令运行正常,但该命令在终端上也运行良好,但不是 python 脚本。

最佳答案

您的命令 是一个只有一个元素的列表。想象一下,如果您尝试在 shell 中运行它:

/bin/'dd if='/dev/'sda8 count=100 skip=$(expr 19868431049 '/' 512)'

这实际上就是您正在做的事情。在你的 bin 目录中几乎可以肯定没有名为 dd if= 的目录,而且几乎可以肯定没有 dev 目录下有一个 sd8 count=100 skip=$(expr 19868431049 目录,其中有一个名为 512 的程序。

你想要的是一个列表,其中每个参数都是它自己的元素:

command = ['/bin/dd', 'if=/dev/sda8', 'count=100', 'skip=$(expr 19868431049 / 512)']
print subprocess.check_output(command) # notice no []

但这给我们带来了第二个问题:$(expr 19868431049/512) 不会被 Python 或 dd 解析;那是 bash 语法。当然,您可以在 Python 而不是 bash 中做同样的事情:

command = ['/bin/dd', 'if=/dev/sda8', 'count=100', 
           'skip={}'.format(19868431049 // 512)]
print subprocess.check_output(command)

或者,如果你真的无缘无故地想使用 bash,传递一个字符串,而不是一个列表,并使用 shell=True:

command = "/bin/dd if=/dev/sda8 count=100 skip=$(expr 19868431049 / 512)"
print subprocess.check_output(command, shell=True) # still no []

虽然这仍然不能移植,因为默认的 shell 是 /bin/sh,它可能不知道如何处理像 $(…) 这样的 bashism >(和 expr,尽管我认为 POSIX 要求 expr 作为一个单独的进程存在……)。所以:

command = "/bin/dd if=/dev/sda8 count=100 skip=$(expr 19868431049 / 512)"
print subprocess.check_output(command, shell=True, executable='/bin/bash')

关于python - subprocess.check_output() : OSError file not found in Python,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29891059/

相关文章:

python - Scipy、tf-idf 和余弦相似度

python - 具有依赖预设参数的函数

python - 在 Google App Engine 上连接 python 后端和 vue.js 前端

python - 尝试从文本文件打印简单列表时出现 'output not utf-8' 错误

python - 如何在 tweepy 的流 API 中使用 'count' 参数?

python - 完全删除 matplotlib 中曲面图上的网格?

python - 使用 QRunnable 进行线程处理 - 发送双向回调的正确方式

python - 如何从列表列表创建字典键?

python - 在 openCV 3 python 2.7 中打开 ffmpeg/mpeg-4 avi

python - 在 python 中使用 enumerate() 时从列表中删除元素