在意外令牌附近获取语法错误`;' 在python中

raj*_*han 4 python

我是Python新手所以请帮帮我...

#!/usr/bin/python -tt

import sys
import commands

def runCommands():
  f = open("a.txt", 'r')
  for line in f:  # goes through a text file line by line
    cmd = 'ls -l ' + line 
    print "printing cmd = " + cmd,
    (status, output) = commands.getstatusoutput(cmd)
  if status:    ## Error case, print the command's output to stderr and exit
      print "error"
      sys.stderr.write(output)
      sys.exit(1)
  print output
  f.close()

def main():
  runCommands()

# Standard boilerplate at end of file to call main() function.
if __name__ == '__main__':
  main()
Run Code Online (Sandbox Code Playgroud)

我运行如下:

$python demo.py
sh: -c: line 1: syntax error near unexpected token `;'
sh: -c: line 1: `; } 2>&1'
error
Run Code Online (Sandbox Code Playgroud)

跑步less $(which python)说:

#!/bin/sh bin=$(cd $(/usr/bin/dirname "$0") && pwd) exec -a "$0" "$bin/python2.5" "$@"
Run Code Online (Sandbox Code Playgroud)

如果我删除for loop然后它工作正常

$cat a.txt
dummyFile


$ls -l dummyFile
-rw-r--r-- 1 blah blah ...................

$python demo.py
printing cmd = ls -l dummyFile
sh: -c: line 1: syntax error near unexpected token `;'
sh: -c: line 1: `; } 2>&1'
error
Run Code Online (Sandbox Code Playgroud)

我正在使用'ls'来表示问题.实际上我想使用一些内部shell脚本,所以我必须以这种方式运行这个python脚本.

Lev*_*von 6

问题是由这条线引起的:

    cmd = 'ls -l ' + line
Run Code Online (Sandbox Code Playgroud)

它应该被修改为:

    cmd = 'ls -l ' + line.strip() 
Run Code Online (Sandbox Code Playgroud)

当您从文本文件中读取该行时,您还会阅读尾随\n.您需要剥离它以使其有效.在getstatusoutput()不喜欢的换行符.看到这个交互式测试(这是我验证它的方式):

In [7]: s, o = commands.getstatusoutput('ls -l dummyFile')

In [8]: s, o = commands.getstatusoutput('ls -l dummyFile\n')
sh: Syntax error: ";" unexpected
Run Code Online (Sandbox Code Playgroud)