无法通过 python 中的 popen 运行 dd 命令

Unable to run dd command via popen in python

代码:

from subprocess import PIPE, Popen
op = Popen("lsblk", shell=True, stdout=PIPE).stdout.read()
print op
a = raw_input("Enter Path of Device to be copied : ",)
b = raw_input("Enter new name for Image : ",)
print a+b
op=Popen("dd if="+a+" of="+b+" bs=512").stdout.read()
print op
op = Popen("fls "+b+"|grep "+c, shell=True, stdout=PIPE).stdout.read()
print op
ar = op.split(" ")
d = ar[1]
op = Popen("istat "+b+" "+d, shell=True, stdout=PIPE).stdout.read()
print op
e = raw_input("Enter new filename")
op = Popen("icat "+b+" "+d+" >> "+e, shell=True, stdout=PIPE).stdout.read()
print op
op = Popen("gedit "+e, shell=True, stdout=PIPE).stdout.read()
print op

错误:

Traceback (most recent call last):   
  File "a3.py", line 8, in <module>
    op=Popen("dd if="+a+" of="+b+" bs=512").stdout.read()
  File "/usr/lib64/python2.7/subprocess.py", line 711, in __init__
    errread, errwrite)
  File "/usr/lib64/python2.7/subprocess.py", line 1327, in _execute_child
    raise child_exception OSError: [Errno 2] No such file or directory

求助,本人不熟悉subprocess.Popen,编程新手

Popen(["command", "-opt", "value", "arg1", "arg2" ...], stdout=PIPE)

您没有正确使用 Popen 功能。这是考虑到您的脚本的一个简短示例:

op = Popen(["dd", "if="+a, "of="+b, "bs=512"], stdout=PIPE)

您应该查看子流程文档(help(subprocess) 在解释器中)

你最好传递一个参数列表,如果你想通过管道传输,你可以使用 Popen 将一个进程的标准输出管道传输到另一个进程的标准输入,如果你只想查看输出,请使用 check_output并将 stdout 重定向到文件,将文件对象传递到 stdout,如下所示:

from subprocess import check_output,check_call, Popen,PIPE

op = check_output(["lsblk"])
print op
a = raw_input("Enter Path of Device to be copied : ", )
b = raw_input("Enter new name for Image : ", )
print a + b
# get output
op = check_output(["dd", "if={}".format(a), "of={}".format(b), "bs=512"])
print op
# pass list of args without shell=True
op = Popen(["fls", b], stdout=PIPE)
# pipe output from op to grep command
op2 = Popen(["grep", c],stdin=op.stdout,stdout=PIPE)
op.stdout.close()
# get stdout from op2
d = op.communicate()[0].split()[1]

op = check_output(["istat",b, d])
print op
e = raw_input("Enter new filename")
# open the file with a to append passing file object to stdout
# same as >> from bash
with open(a, "a") as f:
    check_call(["icat", b], stdout=f)

# open file and read
with open(e) as out:
    print(out.read())

我不确定 c 是从哪里来的,所以你需要确保在某处定义了它,check_callcheck_output 将为任何非零退出引发 CalledProcessError status 所以你可能想用 try/except 捕捉它,所以如果发生错误,任何合适的东西。

您的代码在第一次 Popen 调用时失败,因为您传递的字符串没有 shell=True,您需要像上面的代码一样传递一个参数列表,通常传递一个参数列表而不使用 shell=True 将是更好的方法,尤其是在从用户那里获取输入时。