Python execute windows cmd functions

2019-05-28 11:22发布

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?

4条回答
萌系小妹纸
2楼-- · 2019-05-28 11:43

dir is not a file, it is an internal command, so the shell keyword must be set to True.

subprocess.call(["dir"], shell=True)
查看更多
Ridiculous、
3楼-- · 2019-05-28 11:46

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

查看更多
我欲成王,谁敢阻挡
4楼-- · 2019-05-28 11:50

Try this

import os

os.system("windows command")

ex: for date

os.system("date")

查看更多
小情绪 Triste *
5楼-- · 2019-05-28 11:57

First of all, to get a directory listing, you should rather use os.listdir(). If you invoke dir 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 a cmd.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 of check_call if you need to get the output instead of just printing it):

  • use cmd's /C switch (execute a command and quit):

    subprocess.check_call(['cmd','/c','dir','/s'])
    
  • use shell=True Popen() option (execute command line through the system shell):

    subprocess.check_call('dir /s', shell=True)
    

The first way is the recommended one. That's because:

  • In the 2nd case, 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 and cmd special characters and/or keywords.
  • shell=True uses the "default system shell" (pointed to via COMSPEC environment variable in the case of Windows), so if the user has redefined it, your program will behave unexpectedly.
查看更多
登录 后发表回答