python - python可以运行 "persistent shell"吗

标签 python shell

我正在尝试在同一环境中运行一系列 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.stdinproc.stderr

关于python - python可以运行 "persistent shell"吗,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56415784/

相关文章:

python - 解析 pandas read_json 中的 json 值

python - pandas DataFrame 中行之间的线性插值

python - 获取文本并删除所有标签,但保留标题和粗体的标签

linux - 使用 Shell 脚本解压

html - Unix Shell 中的 CSS 样式覆盖

Python/ Pandas : Eliminate for Loop using 2 DataFrames

python - 基于字符串迭代声明变量?

linux - 我如何从 linux shell 脚本解析 yaml 文件

python - 从 shell 脚本调用 python 函数

bash - 返回命令的 pid 而不是返回 tee pid