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
576k119 gold badges942 silver badges841 bronze badges
asked Mar 30, 2011 at 13:10
4
how about simply:
import os
os.system('dir c:\\')
answered Mar 30, 2011 at 13:19
rmflowrmflow
4,4754 gold badges27 silver badges42 bronze badges
0
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.7k4 gold badges41 silver badges54 bronze badges
answered Mar 30, 2011 at 13:17
Daren ThomasDaren Thomas
68.1k40 gold badges154 silver badges200 bronze badges
7
Try:
import os
os.popen("Your command here")
Wyetro
8,4499 gold badges46 silver badges64 bronze badges
answered Dec 6, 2014 at 7:39
vezon122vezon122
2412 silver badges2 bronze badges
1
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')
answered Jan 22, 2020 at 2:48
AndrewMZAndrewMZ
1711 silver badge4 bronze badges
1
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.
answered Mar 30, 2011 at 14:33
ncoghlanncoghlan
40.3k10 gold badges71 silver badges80 bronze badges
1
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.
answered Feb 28, 2019 at 18:09
gkimseygkimsey
5176 silver badges13 bronze badges
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.
answered Mar 30, 2011 at 13:25
kurumikurumi
25.2k5 gold badges45 silver badges52 bronze badges
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()
.
answered Sep 28, 2021 at 16:41
palschpalsch
5,6584 gold badges21 silver badges32 bronze badges
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!
answered Jan 21, 2021 at 12:23
0
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.
answered Nov 1, 2022 at 19:28
X1525X1525
351 silver badge8 bronze badges
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♦
31.1k25 gold badges87 silver badges138 bronze badges
answered Nov 9, 2020 at 7:00
Abhishek ChaubeyAbhishek Chaubey
2,9601 gold badge17 silver badges24 bronze badges
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
576k119 gold badges942 silver badges841 bronze badges
asked Mar 30, 2011 at 13:10
4
how about simply:
import os
os.system('dir c:\\')
answered Mar 30, 2011 at 13:19
rmflowrmflow
4,4754 gold badges27 silver badges42 bronze badges
0
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.7k4 gold badges41 silver badges54 bronze badges
answered Mar 30, 2011 at 13:17
Daren ThomasDaren Thomas
68.1k40 gold badges154 silver badges200 bronze badges
7
Try:
import os
os.popen("Your command here")
Wyetro
8,4499 gold badges46 silver badges64 bronze badges
answered Dec 6, 2014 at 7:39
vezon122vezon122
2412 silver badges2 bronze badges
1
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')
answered Jan 22, 2020 at 2:48
AndrewMZAndrewMZ
1711 silver badge4 bronze badges
1
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.
answered Mar 30, 2011 at 14:33
ncoghlanncoghlan
40.3k10 gold badges71 silver badges80 bronze badges
1
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.
answered Feb 28, 2019 at 18:09
gkimseygkimsey
5176 silver badges13 bronze badges
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.
answered Mar 30, 2011 at 13:25
kurumikurumi
25.2k5 gold badges45 silver badges52 bronze badges
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()
.
answered Sep 28, 2021 at 16:41
palschpalsch
5,6584 gold badges21 silver badges32 bronze badges
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!
answered Jan 21, 2021 at 12:23
0
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.
answered Nov 1, 2022 at 19:28
X1525X1525
351 silver badge8 bronze badges
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♦
31.1k25 gold badges87 silver badges138 bronze badges
answered Nov 9, 2020 at 7:00
Abhishek ChaubeyAbhishek Chaubey
2,9601 gold badge17 silver badges24 bronze badges
Welcome to Python Run Shell Command On Windows tutorial. In this tutorial, you will learn, how to run shell command in python. So let’s move forward.
What is Shell ?
- In computer science shell is generally seen as a piece of software that provides an interface for a user to some other software or the operating system.
- So the shell can be an interface between the operating system and the services of the kernel of this operating system
Python Modules For Running Shell command
Python provides lots of modules for executing different operations related to operating system.
Generally there are two important modules which are used to run shell command in python.
- Subprocess module
- OS module
Python Run Shell Command Using Subprocess module
The subprocess module allows you to spawn new processes, connect to their input/output/error pipes, and obtain their return codes. This module intends to replace several older modules and functions:
- os.system
- os.spawn*
- os.popen*
- popen2.*
- commands.*
The subprocess module allows users to communicate from their Python script to a terminal like bash or cmd.exe.
Now we will see different functions of subprocess module.
subprocess.call()
call() method create a separate process and run provided command in this process.
Write the following code to implement call() method of subprocess module.
import subprocess subprocess.call(‘dir’, shell=True) |
In this example, we will create a process for dir command
It’s output will be as follows.
subprocess.check_output()
check_output()is used to capture the output for later processing. So let’s see how it works.
import subprocess output = subprocess.check_output(‘dir’, shell=True) print(output) |
Output
Python Run Shell Command Using OS module
The OS module is used to interact with underlying operating system in several different ways.
OS is an python built-in module so we don’t need to install any third party module. The os module allows platform independent programming by providing abstract methods.
Executing Shell scripts with os.system()
The most straight forward approach to run a shell command is by using os.system().
import os os.system(‘dir’) |
Capturing Output
The problem with this approach is in its inflexibility since you can’t even get the resulting output as a variable. os.system() doesn’t return the result of the called shell commands. So if you want to capture output then you have to use os.popen() method.
The os.popen() command opens a pipe from or to the command line. This means that we can access the stream within Python. This is useful since you can now get the output as a variable. Now let’s see it practically, so write the following code.
import os output = os.popen(‘dir’).readlines() print(output) |
- Here i used readlines() function, which splits each line (including a trailing \n).
- You can also use read() method which will get the whole output as one string.
Now it’s output will be as follows.
So guys, that’s it for Python Run Shell Command On Windows tutorial. I hope it is helpful for you and if you have any query regarding this post then ask your questions in comment section. Thanks Everyone.
Related Articles :
- How To Add Code To GitHub Using PyCharm
- Sets In Python Tutorial For Beginners
- Join Two Lists Python – Learn Joining Two Lists With Examples
Need to execute a Command Prompt command from Python?
If so, depending on your needs, you may use either of the two methods below to a execute a Command Prompt command from Python:
(1) CMD /K – execute a command and then remain:
import os os.system('cmd /k "Your Command Prompt Command"')
(2) CMD /C – execute a command and then terminate:
import os os.system('cmd /c "Your Command Prompt Command"')
Still not sure how to apply the above methods in Python?
Let’s then review few examples to better understand how to execute a Command Prompt command from Python.
Method 1 (CMD /K): Execute a command and then remain
To see how to apply the first method in practice, let’s review a simple example where we’ll execute a simple command in Python to:
- Display the current date in the Command Prompt
- The Command Prompt will remain opened following the execution of the command
You may then apply the following code in Python to achieve the above goals:
import os os.system('cmd /k "date"')
Once you run the code in Python, you’ll get the date in the command prompt:
The current date is: Fri 06/25/2021
Enter the new date: (mm-dd-yy)
Now what if you want to execute multiple command prompt commands from Python?
If that’s the case, you can insert the ‘&’ symbol (or other symbols, such as ‘&&’ for instance) in between the commands.
For example, what if you want to display all the characters in the command prompt in green and display the current date?
You can then use the following syntax in Python:
import os os.system('cmd /k "color a & date"')
You’ll now see the current date displayed in green:
The current date is: Fri 06/25/2021
Enter the new date: (mm-dd-yy)
Note that for more complex commands, you may find it useful to run a batch file from Python.
Method 2 (CMD /C): Execute a command and then terminate
For this method, you can execute the same commands as reviewed under the first method, only this time the Command Prompt will be closed following the execution of the commands.
For example, you may apply the following code in Python to change the color of all characters to green:
import os os.system('cmd /c "color a"')
In this case, the command will still get executed, but you may not be able to see it on your monitor.
In general, you can get a useful legend with further information by typing the command below in the Command Prompt:
cmd /?
When it comes to automating tasks or integrating different tools and systems, executing a command prompt command from within a Python script can be a useful skill to have. The ability to run shell commands allows you to use the underlying operating system functionality, such as running executables or interacting with the file system, directly from your Python code. This can be especially helpful in cases where there is no Python module available to accomplish a specific task.
Method 1: Using the subprocess Module
You can execute a command prompt command from Python by using the subprocess
module. This module allows you to spawn new processes, connect to their input/output/error pipes, and obtain their return codes.
Step 1: Import the subprocess Module
Step 2: Define the Command Prompt Command
Step 3: Execute the Command Prompt Command
result = subprocess.run(command, stdout=subprocess.PIPE, stderr=subprocess.PIPE, shell=True)
Step 4: Process the Result
output = result.stdout.decode('utf-8')
errors = result.stderr.decode('utf-8')
Example 1: Execute the «dir» Command and Print the Output
import subprocess
command = 'dir'
result = subprocess.run(command, stdout=subprocess.PIPE, stderr=subprocess.PIPE, shell=True)
output = result.stdout.decode('utf-8')
errors = result.stderr.decode('utf-8')
print(output)
Example 2: Execute the «ipconfig» Command and Save the Output to a File
import subprocess
command = 'ipconfig'
result = subprocess.run(command, stdout=subprocess.PIPE, stderr=subprocess.PIPE, shell=True)
output = result.stdout.decode('utf-8')
errors = result.stderr.decode('utf-8')
with open('ipconfig.txt', 'w') as f:
f.write(output)
Example 3: Execute the «ping» Command with Arguments and Print the Output
import subprocess
ip_address = '127.0.0.1'
command = f'ping {ip_address}'
result = subprocess.run(command, stdout=subprocess.PIPE, stderr=subprocess.PIPE, shell=True)
output = result.stdout.decode('utf-8')
errors = result.stderr.decode('utf-8')
print(output)
Method 2: Using the os Module
To execute a command prompt command from Python using the os
module, you can use the os.system()
function. This function takes a string argument that represents the command you want to execute. Here is an example:
import os
os.system("dir") # for Windows
os.system("ls") # for Unix-like systems
This code will execute the dir
command on Windows or the ls
command on Unix-like systems. The os.system()
function will return the exit status of the command, which you can use to check if the command executed successfully.
You can also use the subprocess
module to execute command prompt commands from Python. Here is an example:
import subprocess
result = subprocess.run("dir", shell=True, stdout=subprocess.PIPE, stderr=subprocess.PIPE, universal_newlines=True) # for Windows
result = subprocess.run("ls", shell=True, stdout=subprocess.PIPE, stderr=subprocess.PIPE, universal_newlines=True) # for Unix-like systems
print(result.stdout)
This code will execute the dir
command on Windows or the ls
command on Unix-like systems using the subprocess.run()
function. The stdout
argument is used to capture the output of the command, which is then printed to the console.
In summary, you can execute command prompt commands from Python using the os.system()
or subprocess.run()
function. The os.system()
function is simpler but less flexible, while the subprocess.run()
function is more powerful but more complex.
Method 3: Using the Popen Method in the subprocess Module
To execute a command prompt command from Python, you can use the subprocess
module. Specifically, the Popen
method allows you to spawn a new process and execute a command in that process. Here’s an example code to execute a command prompt command using the Popen
method:
import subprocess
command = 'dir'
process = subprocess.Popen(command, stdout=subprocess.PIPE, shell=True)
output, error = process.communicate()
print(output.decode('utf-8'))
In the above code, we first define the command to be executed as a string. We then use the Popen
method to execute the command. The stdout
argument is set to subprocess.PIPE
to capture the output of the command. The shell
argument is set to True
to allow the use of shell commands such as dir
. Finally, we use the communicate
method to capture the output of the command and wait for the process to complete. The output is then printed to the console.
Here’s another example that shows how to execute a command with arguments:
import subprocess
command = ['echo', 'Hello, World!']
process = subprocess.Popen(command, stdout=subprocess.PIPE)
output, error = process.communicate()
print(output.decode('utf-8'))
In this example, we define the command as a list of strings, where the first string is the command itself and the subsequent strings are the arguments. We then use the Popen
method to execute the command, similar to the previous example.
These are just a few examples of how to use the Popen
method in the subprocess
module to execute command prompt commands from Python. For more details and options, refer to the official Python documentation for the subprocess
module.