Command to run: ls -l . '{' is not recognized as an internal or external command, operable program or batch file

StackOverflow https://stackoverflow.com/questions/23517686

  •  17-07-2023
  •  | 
  •  

質問

I have such code in file hello.py:

import sys
import os
import commands

def listdir(dir):
  cmd = 'ls -l ' + dir
  print ("Command to run:", cmd)   ## good to debug cmd before actually running it
  (status, output) = commands.getstatusoutput(cmd)
  if status:    ## Error case, print the command's output to stderr and exit
    sys.stderr.write(output)
    sys.exit(1)
  print (output)  ## Otherwise do something with the command's output


def main():

 listdir(sys.argv[1])

if __name__ == '__main__':
  main()

I run it from cmd like:

$ hello.py .

But got error:

Command to run: ls -l .
'{' is not recognized as an internal or external command,
operable program or batch file.

Could someone help me to refine what is the problem with my code (I got it from google tutorials). python version is 2.7

役に立ちましたか?

解決

From python Standard Library manual :

commands.getstatusoutput(cmd) 
Execute the string cmd in a shell with os.popen() and return a 2-tuple (status, output).
cmd is actually run as { cmd ; } 2>&1, so that the returned output will contain output or
error messages. A trailing newline is stripped from the output. The exit status for the
command can be interpreted according to the rules for the C function wait().

The syntax {} is correctily interpreted by Linux or other Unix like shells, but not by Windows cmd.exe.

As others suggested to, try to use subprocess ... and read the manual ...

ライセンス: CC-BY-SA帰属
所属していません StackOverflow
scroll top