59

I tried something like this, but with no effect:

command = "cmd.exe"
proc = subprocess.Popen(command, stdin = subprocess.PIPE, stdout = subprocess.PIPE)
proc.stdin.write("dir c:\\")
Sven Marnach
  • 574,206
  • 118
  • 941
  • 841
Adrian
  • 19,440
  • 34
  • 112
  • 219

11 Answers11

91

how about simply:

import os
os.system('dir c:\\')
rmflow
  • 4,445
  • 4
  • 27
  • 41
40

You probably want to try something like this:

command = "cmd.exe /C dir C:\\"

I don't think you can pipe into cmd.exe... If you are coming from a unix background, well, cmd.exe has some ugly warts!

EDIT: According to Sven Marnach, you can pipe to cmd.exe. I tried following in a python shell:

>>> import subprocess
>>> proc = subprocess.Popen('cmd.exe', stdin = subprocess.PIPE, stdout = subprocess.PIPE)
>>> stdout, stderr = proc.communicate('dir c:\\')
>>> stdout
'Microsoft Windows [Version 6.1.7600]\r\nCopyright (c) 2009 Microsoft Corporatio
n.  All rights reserved.\r\n\r\nC:\\Python25>More? '

As you can see, you still have a bit of work to do (only the first line is returned), but you might be able to get this to work...

AlG
  • 14,697
  • 4
  • 41
  • 54
Daren Thomas
  • 67,947
  • 40
  • 154
  • 200
  • For testing, I started Windows XP inside a VirtualBox and tried `echo dir | cmd` -- works fine. So you *can* pipe to `cmd.exe`. – Sven Marnach Mar 30 '11 at 13:23
  • @Sven Marnach: You are right, it seems to work, I have updated my answer. – Daren Thomas Mar 30 '11 at 14:12
  • 1
    As I noted in my answer, failing to terminate the command with `"\n"` and failing to explicitly flush the pipe are the two prime candidates I can see as to why the poster's code isn't producing anything on `proc.stdout`. (I missed that Sven had already mentioned flushing the pipe in the comments) – ncoghlan Mar 30 '11 at 14:36
  • 1
    After testing the answer in anaconda with (I)python3 on Windows10 i get an error: `TypeError: a bytes-like object is required, not 'str' `. Can anybody confirm that it don't work on Windows10, python3 or anaconda? – Jan-Bert Sep 08 '17 at 07:35
  • 3
    @Jan-Bert Try putting `b` before it like so: `b'byte string here'`. This is probably due to this answer's age and that it's using Python 2, not 3. Check out https://docs.python.org/3/howto/pyporting.html#text-versus-binary-data. – GeeTransit Apr 16 '19 at 00:19
  • I tried this with python 3.7 on windows, getting error as ```TypeError: a bytes-like object is required, not 'str'``` – sattva_venu Sep 24 '20 at 13:51
  • @sattva_venu, in Python 3, you'll have to _encode_ the string. – Daren Thomas Sep 25 '20 at 14:04
24

Try:

import os

os.popen("Your command here")
Wyetro
  • 8,439
  • 9
  • 46
  • 64
vezon122
  • 241
  • 2
  • 2
17

Using ' and " at the same time works great for me (Windows 10, python 3)

import os
os.system('"some cmd command here"')

for example to open my web browser I can use this:

os.system(r'"C:\Program Files (x86)\Google\Chrome\Application\chrome.exe"')

(Edit) for an easier way to open your browser I can use this:

import webbrowser
webbrowser.open('website or leave it alone if you only want to open the 
browser')
Jean-François Fabre
  • 137,073
  • 23
  • 153
  • 219
AndrewMZ
  • 171
  • 1
  • 4
7

Try adding a call to proc.stdin.flush() after writing to the pipe and see if things start behaving more as you expect. Explicitly flushing the pipe means you don't need to worry about exactly how the buffering is set up.

Also, don't forget to include a "\n" at the end of your command or your child shell will sit there at the prompt waiting for completion of the command entry.

I wrote about using Popen to manipulate an external shell instance in more detail at: Running three commands in the same process with Python

As was the case in that question, this trick can be valuable if you need to maintain shell state across multiple out-of-process invocations on a Windows machine.

Community
  • 1
  • 1
ncoghlan
  • 40,168
  • 10
  • 71
  • 80
6

Taking some inspiration from Daren Thomas's answer (and edit), try this:

proc = subprocess.Popen('dir C:\\', shell=True, stdin=subprocess.PIPE, stdout=subprocess.PIPE)
out, err = proc.communicate()

out will now contain the text output.

They key nugget here is that the subprocess module already provides you shell integration with shell=True, so you don't need to call cmd.exe directly.

As a reminder, if you're in Python 3, this is going to be bytes, so you may want to do out.decode() to convert to a string.

gkimsey
  • 517
  • 6
  • 13
3

Why do you want to call cmd.exe ? cmd.exe is a command line (shell). If you want to change directory, use os.chdir("C:\\"). Try not to call external commands if Python can provide it. In fact, most operating system commands are provide through the os module (and sys). I suggest you take a look at os module documentation to see the various methods available.

kurumi
  • 25,121
  • 5
  • 44
  • 52
3

Here's a way to just execute a command line command and get its output using the subprocess module:

import subprocess
# You can put the parts of your command in the list below or just use a string directly.
command_to_execute = ["echo", "Test"]

run = subprocess.run(command_to_execute, capture_output=True)

print(run.stdout) # the output "Test"
print(run.stderr) # the error part of the output

Just don't forget the capture_output=True argument and you're fine. Also, you will get the output as a binary string (b"something" in Python), but you can easily convert it using run.stdout.decode().

palsch
  • 5,528
  • 4
  • 21
  • 32
2

It's very simple. You need just two lines of code with just using the built-in function and also it takes the input and runs forever until you stop it. Also that 'cmd' in quotes, leave it and don't change it. Here is the code:

import os
os.system('cmd')

Now just run this code and see the whole windows command prompt in your python project!

1

In Python, you can use CMD commands using these lines :

import os 

os.system("YOUR_COMMAND_HERE") 

Just replace YOUR_COMMAND_HERE with the command you like.

X1525
  • 35
  • 1
  • 8
-1

From Python you can do directly using below code

import subprocess
proc = subprocess.check_output('C:\Windows\System32\cmd.exe /k %windir%\System32\\reg.exe ADD HKLM\SOFTWARE\Microsoft\Windows\CurrentVersion\Policies\System /v EnableLUA /t REG_DWORD /d 0 /f' ,stderr=subprocess.STDOUT,shell=True)
    print(str(proc))

in first parameter just executed User Account setting you may customize with yours.

Dharman
  • 30,962
  • 25
  • 85
  • 135
Abhishek Chaubey
  • 2,960
  • 1
  • 17
  • 24