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

时间:2015-07-20 11:47:01

标签: python terminal subprocess popen dd

代码:

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并且是编程新手。

2 个答案:

答案 0 :(得分:0)

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

您没有以正确的方式使用Popen功能。以下是考虑您的脚本的简短示例:

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

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

答案 1 :(得分:0)

你最好传递一个args列表,如果你想管道你可以使用Popen将一个进程的stdout传递给另一个进程的stdin,如果你想看到输出使用check_output并将stdout重定向到一个file将文件对象传递给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,你可能希望用try / except来捕获它,所以如果发生错误则适当。

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

相关问题