0

I'm attempting to write a python script that will open the command prompt and change directories to a git initialized folder and return the git status. For right now I'd like help with how to just show the current directories so I can try and work through the solution myself.

import subprocess

p = subprocess.Popen(['cmd.exe','dir'])

I expected this to show me my current directories but it just returns what I normally see when I open the command prompt. What would be the proper way to do this and pass on multiple commands?

2
  • did you try to run "cmd.exe dir" in command line to see how it works ? You can also check "cmd.exe --help" - probably it should show what options you can use with "cmd.exe" Commented Aug 7, 2019 at 23:26
  • "FileNotFoundError: [WinError 2] The system cannot find the file specified" was the error I received when I tried that. Commented Aug 7, 2019 at 23:45

1 Answer 1

2

Instead of explicitly using cmd.exe inside of Popen, you could use shell=True, which basically does the same (and is way better considering you might want to execute your script on different operating systems).

If you want to get the results of your executed command, you can redirect the output with the stdout and stderr parameter to subprocess.PIPE, which than can be grabbed with p.stdout.readlines().

So your required solution would be

import subprocess

p = subprocess.Popen('dir', shell=True, stdout=subprocess.PIPE, stderr=subprocess.STDOUT)
for line in p.stdout.readlines():
    print(line)
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.