我正在寻找使用Python为Windows创build一个diskpart脚本。
我需要运行diskpart,然后在执行程序之后发出附加命令,下面是一系列input。 我最终会把它放在一个循环中,这样可以完成一系列的磁盘。
我试图做到这一点如下。
在下面的例子中,我能够执行diskpart,然后运行第一个命令,即“select磁盘1”,然后终止。 我希望能够发送额外的命令来完成准备磁盘的过程如何完成? 除了从文件中读取数据外,diskpart并没有采取可以促进这一点的参数,但是我想避免在Windows 2012 PowerShell cmdelts中这样做,这样做更容易实现。
import subprocess from subprocess import Popen, PIPE, STDOUT p = Popen(['diskpart'], stdout=PIPE, stdin=PIPE, stderr=STDOUT) grep_stdout = p.communicate(input=b'select disk 1')[0] print(grep_stdout.decode())
寻找沿线的东西
from subprocess import Popen, PIPE, STDOUT p = Popen(['diskpart'], stdout=PIPE, stdin=PIPE, stderr=STDOUT) grep_stdout = p.communicate(input=b'select disk 1')[0] - run command - run command - run command - run command - run command - run command - run command print(grep_stdout.decode())
我尝试了下面的实际执行diskpart,然后也运行命令“select磁盘1”,然后退出,我相信这是不是正确的方式发送input,但更多的是我想要实现的东西如果我可以继续发送后续命令。
import subprocess from subprocess import Popen, PIPE, STDOUT p = Popen(['diskpart'], stdout=PIPE, stdin=PIPE, stderr=STDOUT) grep_stdout = p.communicate(input=b'select disk 1')[0]
我认为在这里communicate
有问题 – 它将数据发送到流程,然后等待它完成。 (请参阅多次使用进程进行通信而不会中断管道? )
我不确定这会有帮助,但我写了一个基于链接的答案的批处理脚本。
test.bat的:
@echo off set /p animal= "What is your favourite animal? " echo %animal% set /p otheranimal= "What is another awesome animal? " echo %otheranimal% set "animal=" set "otheranimal="
test.py:
import time from subprocess import Popen, PIPE p = Popen(["test.bat"], stdin=PIPE) print("sending data to STDIN") res1 = p.stdin.write("cow\n") time.sleep(.5) res2 = p.stdin.write("velociraptor\n")
这通过将数据发送到stdin,但不等待该过程完成。
我不是一个Windows专家,所以我很抱歉,如果在diskpart
的输入处理工作不同于批处理文件的标准输入。
随着蒂姆斯的帮助,我能够做到以下让我的脚本工作。
import time from subprocess import Popen, PIPE p = Popen(["diskpart"], stdin=PIPE) print("sending data to STDIN") res1 = p.stdin.write(bytes("select disk 2\n", 'utf-8')) time.sleep(.5) res2 = p.stdin.write(bytes("ATTRIBUTES DISK CLEAR READONLY\n", 'utf-8')) time.sleep(.5) res3 = p.stdin.write(bytes("online disk noerr\n", 'utf-8')) time.sleep(.5) res4 = p.stdin.write(bytes("clean\n", 'utf-8')) time.sleep(.5) res5 = p.stdin.write(bytes("create part pri\n", 'utf-8')) time.sleep(.5) res6 = p.stdin.write(bytes("select part 1\n", 'utf-8')) time.sleep(.5) res7 = p.stdin.write(bytes("assign\n", 'utf-8')) time.sleep(.5) res8 = p.stdin.write(bytes("FORMAT FS=NTFS QUICK \n", 'utf-8')) time.sleep(.5)