我正在尝试在同一环境中运行一系列 shell 命令:
相同的导出变量、持久历史记录等
我想在运行下一个命令之前处理每个命令的输出。
查看 python subprocess.run 后和 Pexpect.spawn似乎两者都没有提供这两种功能。
subprocess.run 允许我运行一个命令,然后检查输出,但不能为另一命令保持开放环境。
Pexpect.spawn("bash") 允许我在同一环境中运行多个命令,但直到 EOF 才能获得输出;当 bash 本身退出时。
理想情况下,我想要一个可以同时执行这两项操作的界面:
shell = bash.new()
shell.run("export VAR=2")
shell.run("whoami")
print(shell.exit_code, shell.stdout())
# 0, User
shell.run("echo $VAR")
print(shell.stdout())
# 2
shell.run("!!")
print(shell.stdout())
# 2
shell.run("cat file -")
shell.stdin("Foo Bar")
print(shell.stdout())
# Foo Bar
print(shell.stderr())
# cat: file: No such file or directory
shell.close()
最佳答案
听起来像是 Popen 的例子。您可以指定 bufsize
来禁用缓冲(如果它妨碍的话)。
链接页面的示例:
with Popen(["ifconfig"], stdout=PIPE) as proc:
log.write(proc.stdout.read())
还有用于发送更多命令的 proc.stdin
和 proc.stderr
。
关于python - python可以运行 "persistent shell"吗,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56415784/