Skip to main content
Stack Overflow
  1. About
  2. For Teams

You are not logged in. Your edit will be placed in a queue until it is peer reviewed.

We welcome edits that make the post easier to understand and more valuable for readers. Because community members review edits, please try to make the post substantially better than how you found it, for example, by fixing grammar or adding additional resources and hyperlinks.

Required fields*

Required fields*

Running windows shell commands with python

How can we interact with OS shell using Python ? I want to run windows cmd commands via python. How can it be achieved ?

Answer*

Draft saved
Draft discarded
Cancel
9
  • This works in Windows 7. Thanks. It does return \r\n at the end of the string, so you might need to strip that out with a [0:-2] substring. Commented Apr 17, 2015 at 18:49
  • 7
    Using [0:-2] for that purpose makes me nervous. If anyone takes that code to apply it in a non-Windows context, they'll certainly change the obvious dir C: to ls or whatever. But they could easily fail to realize that [0:-2] should be changed to [0:-1]. I'd recommend .rstrip() instead, which would work on any platform (unless you want to capture other trailing whitespace), and also makes the reason behind the string alteration clearer. Commented May 18, 2015 at 14:11
  • @Mikw: I have a windows command which is used for deployment.Just a single line of command. How can I call it from an external python3.4 script Commented Jun 4, 2015 at 4:54
  • 2
    Works in Win 10 with a slight modification: check_output("dir C:\\", shell=True) Commented Nov 15, 2017 at 16:56
  • 1
    @codingbruh Yes. In fact (as I noted in a previous comment), I don't even have access to any windows machines. I use it routinely on macOS and various species of linux without any trouble. You just need to give it commands that the shell will understand — e.g., ls / instead of dir C:. Commented Nov 21, 2022 at 21:10

default

AltStyle によって変換されたページ (->オリジナル) /