I'm afraid that you'll have to do better than that.
Each subprocess.Popen
command is executed in a separate process, so the change directory command you're issuing in the first call has only a local effect and has no effect on the others.
For other commands it would work, though. You would "just" have to handle the built-in commands separately.
I wrote a simple loop to get you started. For proper quote parsing, I have used the convenient 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))
Features:
- cd
command is handled in a special way. Performs an os.chdir
so you can use relative paths. You can also check the path and forbid cd'ing in some directories if you want.
- since os.chdir
is performed, the next call to subprocess.Popen
is done in the changed directory, retaining the previous cd
command, as opposed to your attempt.
- handles quotes (using shlex module, maybe has its differences with windows cmd!)
- failed commands print return code
- if directory doesn't exist, prints an error instead of crashing :)
Of course it is very limited, no env. variable set, no cmd emulation, that's not the point.
small test:
> 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
>