Shrinivas Patgar
Shrinivas Patgar

Reputation: 121

How to execute cmd.exe with arguments in Python

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

Upvotes: 3

Views: 13524

Answers (3)

Ali Ismayilov
Ali Ismayilov

Reputation: 1755

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)

Upvotes: 2

Jobin
Jobin

Reputation: 6984

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

Upvotes: 8

A'zam Mamatmurodov
A'zam Mamatmurodov

Reputation: 370

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")

Upvotes: 0

Related Questions