繁体   English   中英

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

[英]getting syntax error near unexpected token `;' in 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()

我运行如下:

$python demo.py
sh: -c: line 1: syntax error near unexpected token `;'
sh: -c: line 1: `; } 2>&1'
error

less $(which python)运行less $(which python)说:

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

如果我删除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

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

问题是由这条线引起的:

    cmd = 'ls -l ' + line

它应该被修改为:

    cmd = 'ls -l ' + line.strip() 

当您从文本文件中读取行时,您还会读取尾随\\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

这似乎是“python”命令的一个问题,也许它是一个shell包装脚本或其他东西。

$ less $(which python)

更新

尝试直接调用Python可执行文件,它似乎在/usr/bin/python2.5

$ /usr/bin/python2.5 demo.py

命令模块文档说明运行getstatusoutput(cmd)

cmd实际上是以{ cmd ; } 2>&1 { cmd ; } 2>&1

这应该解释一下; } 2>&1 ; } 2>&1来自。

我的第一个猜测是问题是由于没有从你从文件中读取的每一行的末尾剥离换行,所以你实际运行的命令是这样的

{ ls -l somedir
; } 2>&1

但是,我不太了解shell编程,所以我不知道sh将如何处理{ ... }分割超过两行的内容,也不知道为什么当现在有两行时它会在第1行报告问题线。

第二个猜测是你的文件中有一个空行,在这种情况下, sh可能会抱怨,因为它正在为ls寻找一个参数并且它找到了; } 2>&1 ; } 2>&1代替。

第三个猜测是其中一个文件包含一个} ,或者一个; 然后是}

最终,如果没有看到文件a.txt的内容,我无法确定问题是什么。

顺便说一句,我希望这个文件不包含一行/ && sudo rm -rf / ,因为这可能会导致一两个问题。

从其他地方得到这个答案:

当您将文件作为迭代器进行迭代时,不会剥离换行符。 以下是您的脚本正在执行的实际操作。 您在print语句中有一个逗号(以及输出中的换行符)这一事实就是赠品。

ls -l dummyFile \n

哪些命令解释为

{ ls -l dummyFile
; } 2>&1

调用line.rstrip()(或只是strip)来修复它。

cmd = 'ls -l ' + line.strip()

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM