恐怕你必须做得更好。
每个subprocess.Popen 命令都在单独的进程中执行,因此您在第一次调用中发出的更改目录命令只有本地效果,对其他命令没有影响。
不过,对于其他命令,它会起作用。您将“只”必须单独处理内置命令。
我写了一个简单的循环让你开始。为了正确解析引号,我使用了方便的shlex module
import subprocess,os,shlex
while True:
command = input("> ").strip()
if command:
# tokenize the command, double quotes taken into account
toks = shlex.split(command)
if toks[0] == "cd" and len(toks)==2:
newdir = toks[1]
try:
os.chdir(newdir)
except Exception as e:
print("Failed {}".format(str(e)))
else:
print("changed directory to '{}'".format(newdir))
else:
p = subprocess.Popen(command,shell=True)
rc=p.wait()
if rc:
print("Command failed returncode {}".format(rc))
特点:
- cd 命令以特殊方式处理。执行os.chdir,以便您可以使用相对路径。如果需要,您还可以检查路径并禁止在某些目录中进行 cd'ing。
- 由于执行了os.chdir,下一次调用subprocess.Popen 在更改后的目录中完成,保留之前的cd 命令,而不是您的尝试。
- 处理引号(使用 shlex 模块,可能与 windows cmd 有区别!)
- 失败的命令打印返回码
- 如果目录不存在,打印一个错误而不是崩溃:)
当然是非常有限的,没有环境。变量集,没有 cmd 仿真,这不是重点。
小测试:
> cd ..
changing directory to ..
> cd skdsj
changing directory to skdsj
Failed [WinError 2] Le fichier spécifié est introuvable: 'skdsj'
> dir
Le volume dans le lecteur C s’appelle Windows
Le numéro de série du volume est F08E-C20D
Répertoire de C:\DATA\jff\data\python\stackoverflow
12/10/2016 21:28 <DIR> .
12/10/2016 21:28 <DIR> ..
12/10/2016 21:28 <DIR> ada
08/10/2016 11:11 902 getopt.sh
09/10/2016 20:14 493 iarray.sh
19/08/2016 12:28 <DIR> java
16/11/2016 21:57 <DIR> python
08/10/2016 22:24 51 toto.txt
10 fichier(s) 2,268 octets
10 Rép(s) 380,134,719,488 octets libres
>