I know you can run Linux terminal commands through Python scripts using subprocess
subprocess.call(['ls', '-l']) # for linux
But I can't find a way to do the same thing on windows
subprocess.call(['dir']) # for windows
is it possible using Python without heavy tinkering?
Should I stick to good old fashioned batch files?
dir is not a file, it is an internal command, so the shell keyword must be set to True.
Almost everyone's answers are right but it seems I can do what I need using os.popen --
varStr = os.popen('dir /b *.py').read()
Try this
import os
os.system("windows command")
ex: for date
os.system("date")
First of all, to get a directory listing, you should rather use
os.listdir()
. If you invokedir
instead, you'll have to parse its output to make any use of it, which is lots of unnecessary work and is error-prone.Now,
dir
is acmd.exe
built-in command, it's not a standalone executable.cmd.exe
itself is the executable that implements it.So, you have two options (use
check_output
instead ofcheck_call
if you need to get the output instead of just printing it):use
cmd
's/C
switch (execute a command and quit):use
shell=True
Popen()
option (execute command line through the system shell):The first way is the recommended one. That's because:
cmd
, will do any shell transformations that it normally would (e.g. splitting the line into arguments, unquoting, environment variable expansion etc). So, your arguments may suddenly become something else and potentially harmful. In particular, if they happen to contain any spaces andcmd
special characters and/or keywords.shell=True
uses the "default system shell" (pointed to viaCOMSPEC
environment variable in the case of Windows), so if the user has redefined it, your program will behave unexpectedly.