3

I was trying to run cmd.exe with argument ls.

I used the below code

import subprocess
subprocess.call(['C:\Windows\System32\cmd.exe', 'ls'])

After executing this cmd.exe is opening but not taking ls as input

3
  • because ls is not a recognized command in Windows. Commented Jun 24, 2016 at 11:37
  • ls is not available. Why don't you use the os package? Commented Jun 24, 2016 at 11:40
  • Does ls work when you input it into a cmd shell ? Commented Jun 24, 2016 at 11:56

3 Answers 3

8

There are two mistake in your script

  1. ls not supported in windows use dir instead
  2. /C parameter needed to run a command

Modified script is

>>> import subprocess
>>> subprocess.call(['C:\\windows\\system32\\cmd.exe', '/C', 'dir'])

Note: Use \ to escape backslash character

Sign up to request clarification or add additional context in comments.

1 Comment

I got the below code from somewhere and tried and is working code subprocess.Popen(['cmd','/K','cd ..'])
2

If you add argument shell=True, python will use default shell which is available. In this case, python will use Windows cmd. In other word, below code should work:

>>> subprocess.call('dir', shell=True)

Comments

0

I think , it doesn't work with windows , if you want to use linux syntax in windows you have to use cygwin environment. or change command "ls" to "dir" ("dir /w")

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.