Rony Cohen Rony Cohen - 8 months ago 54
Python Question

Subprocess python without closing the cmd

I want to create a function that have entire access to the cmd of my windows pc. So for example like in windows I can do cd C:\Users\Rony\Documents\Hello and after that run a dir in order to view the files in the current folder and until I run the command exit the cmd doesn't exit. I want to be able to do the same thing in python, I see that I have to use the function popen of the subprocess. But I don't understand how to this in the documentation of python. I try do do something but I don't success to do this.

def run_cmd():
subprocess.Popen("cd C:\Users\Rony\Documents\Apple", shell=True)

Thanks for your help !

Answer Source

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]
            except Exception as e:
                print("Failed {}".format(str(e)))
                print("changed directory to '{}'".format(newdir))
            p = subprocess.Popen(command,shell=True)
            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
09/10/2016  20:14               493
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