1

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)
subprocess.Popen("dir\n")

Thanks for your help !

Rony Cohen
  • 87
  • 2
  • 14
  • It is something very similar to [this one](http://stackoverflow.com/questions/9322796/keep-a-subprocess-alive-and-keep-giving-it-commands-python). Starting from that answer, you should use the command to open a "shell" in windows instead of `/usr/bin/cat`. Probably the command you should use is similar to `C:\WINDOWS\system32\WindowsPowerShell\v1.0\powershell.exe`. BTW, this is not an easy task, you should deepen the problem reading the documentation: – Riccardo Petraglia Nov 16 '16 at 20:55
  • [This is a start...](http://stackoverflow.com/documentation/python/1393/subprocess-library#t=201611162059578672205) – Riccardo Petraglia Nov 16 '16 at 21:01

1 Answers1

1

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
>
Jean-François Fabre
  • 137,073
  • 23
  • 153
  • 219
  • Thanks you ! But I don't understand what is the newdir = shlex.split(command)[1] can you explain this. Moreover I don't understand how you do that the code is based on the previous result to give the result with cd and dir ? ( The code work but I want to understand what you do) – Rony Cohen Nov 16 '16 at 21:33
  • code improved. link to shlex documentation (parses command line & quotes). `cd somedir` is a special case that triggers an internal python `os.chdir()`, so next `subprocess.Popen` command executes in that new directory. – Jean-François Fabre Nov 16 '16 at 21:39