我正在寻找使用 Python 为 Windows 创建一个 diskpart 脚本。
我需要运行 diskpart,然后在执行程序后发出其他命令,一系列输入如下。我最终会将其放入循环中,以便可以对一系列磁盘完成。
- 选择磁盘 1
- 属性磁盘只读
- 在线磁盘noerr
- 干净
- 创建 PRI 部分
- 选择第 1 部分
- 分配
- FORMAT FS=NTFS QUICK LABEL="新卷"
我尝试按如下方式执行此操作。
在下面的示例中,我能够执行 diskpart,然后运行第一个命令“select disk 1”,然后它终止。我希望能够发送附加命令来完成准备磁盘的过程,如何才能做到这一点?除了从文件中读取之外,diskpart 不接受可以促进此目的的参数,但我想避免在 Windows 2012 PowerShell cmdelt 上使此操作更容易实现。
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 disk 1”并退出,我相信这不是发送输入的正确方法,但更符合我正在尝试的方式来实现是否可以继续发送后续命令。
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
方面遇到问题 - 它将数据发送到进程,然后等待它完成。 (参见Communicate multiple times with a process without breaking the pipe?)
我不确定这是否有帮助,但我根据链接的答案编写了一个批处理脚本。
测试.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="
测试.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")
这通过将数据发送到标准输入来工作,但不等待该过程完成。
我不是 Windows 专家,因此如果 diskpart
中的输入处理与批处理文件的标准输入不同,我深表歉意。
关于执行外部程序后可以发送多个输入的Python脚本,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28974921/