python 的流程自动化

automation of processes by python

我正在尝试编写一个 python 脚本来启动一个进程并在后面执行一些操作。 我想通过脚本自动执行的命令在图中用红色圈出。 问题是在执行第一个命令后,qemu 环境将是 运行 而其他命令应该在 qemu 环境中执行。所以我想知道如何通过 python 中的脚本执行这些命令?因为据我所知,我可以执行第一个命令,但我不知道在进入 qemu 环境时如何执行这些命令。

你能帮我看看我该怎么做吗?

别忘了 Python 包含 电池 。查看标准库中的 Suprocess module 。管理流程有很多陷阱,模块会处理所有这些问题。

您可能想要启动一个 qemu 进程并将下一个命令发送到其标准输入 (stdin)。子流程模块将允许您这样做。看到qemu有command line options连接到stdi:-chardev stdio ,id=id

首先想到的是 pexpect, a quick search on google turned up this blog post automatically-testing-vms-using-pexpect-and-qemu,这似乎与您所做的大致相同:

import pexpect

image = "fedora-20.img"
user = "root"
password = "changeme"

# Define the qemu cmd to run
# The important bit is to redirect the serial to stdio
cmd = "qemu-kvm"
cmd += " -m 1024 -serial stdio -net user -net nic"
cmd += " -snapshot -hda %s" % image
cmd += " -watchdog-action poweroff"

# Spawn the qemu process and log to stdout
child = pexpect.spawn(cmd)
child.logfile = sys.stdout

# Now wait for the login
child.expect('(?i)login:')

# And login with the credentials from above
child.sendline(user)
child.expect('(?i)password:')
child.sendline(password)
child.expect('# ')

# Now shutdown the machine and end the process
if child.isalive():
    child.sendline('init 0')
    child.close()

if child.isalive():
    print('Child did not exit gracefully.')
else:
    print('Child exited gracefully.')

您也可以使用 subprocess.Popen 来完成,检查 (qemu) 行的标准输出并写入标准输入。大致是这样的:

from subprocess import Popen,PIPE

# pass initial command as list of individual args
p = Popen(["./tracecap/temu","-monitor",.....],stdout=PIPE, stdin=PIPE)
# store all the next arguments to pass
args = iter([arg1,arg2,arg3])
# iterate over stdout so we can check where we are
for line in iter(p.stdout.readline,""):
    # if (qemu) is at the prompt, enter a command
    if line.startswith("(qemu)"):
        arg = next(args,"") 
        # if we have used all args break
        if not arg:
            break
        # else we write the arg with a newline
        p.stdin.write(arg+"\n")
    print(line)# just use to see the output

其中 args 包含所有后续命令。