我正在尝试在 python 中创建一个简单的脚本,它本质上是一个 shell 终端。它会反复要求输入命令并尝试执行给定的操作系统命令。我想不通的是如何让 Python“记住”已执行的命令。
我的意思的例子:
- 用户输入
ls
- Python 打印当前目录的内容
- 下一个用户输入
cd exampledir
- Python执行命令
- 用户输入
ls
- Python 打印
exampledir
的内容
由于命令序列是 ls
> cd exampledir
> ls
我希望程序返回 exampledir 的内容,而不是两个 ls
命令的输出是相同的。
有没有办法让 Python 以某种方式“记住”已执行的命令并根据之前的命令执行下一条命令?
我知道您可以使用 cd exampledir && ls
之类的东西,但这不是我要找的。这些命令必须像在 shell 终端中一样单独执行。
到目前为止的代码:
import subprocess
while True:
cmd = input("Command to Execute: ")
p = subprocess.Popen(cmd, shell=True, stdout=subprocess.PIPE, stderr=subprocess.STDOUT)
out = p.communicate()[0]
print(out)
最佳答案
你不能用 cd
输出 subprocess
模块,该函数将运行但路径不会改变正在运行的 python 脚本,
你可以做的是:
import os
if # condition where cd command used:
os.chdir("path/to/new/dir")
这将更改您正在运行的 python 脚本的路径,然后您可以 ls
获得不同的输出。
关于python - 在python中执行相关os命令,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39798453/