2012-06-05 75 views
3

我是一個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)說:

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

如果我刪除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腳本。

+1

我剛剛運行您的代碼。它運行良好。 – pyfunc

+0

然後在我的末尾有什麼問題:( –

+0

我正在運行此命令 - $ python demo.py –

回答

4

問題是由這一行造成的:

cmd = 'ls -l ' + line 

,應修改爲:

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

當你閱讀您的文本文件中的行,你也可以參考尾隨\n。你需要strip這樣才能工作。 getstatusoutput()不喜歡尾隨換行符。看到這個交互式測試(這是我如何驗證它):

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

In [8]: s, o = commands.getstatusoutput('ls -l dummyFile\n') 
sh: Syntax error: ";" unexpected 
+0

我是runni ng這個命令 - $ python demo.py –

+0

我在我公司的linux env上運行這個,是否有可能已經改變了核心python lib? –

+0

是的,如果我刪除for循環然後它工作正常 –

2

這似乎是「python」命令的問題,也許是shell封裝腳本或其他東西。

運行

$ less $(which python) 

UPDATE

嘗試調用Python的直接執行,這似乎是在/usr/bin/python2.5

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

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

+0

沒有運氣...跑$/usr/bin/python2 demo.py ...同樣的輸出 –

+0

'a.txt' - 特別是'a.txt'的_last行 - 在這裏很重要,也就是說,在腳本中使用'ls'是邪惡的;如果你使用Python的'os.listdir()'想要獲取目錄內容,但ls甚至不應該在shell腳本中解析;請參閱http://mywiki.wooledge.org/ParsingLs –

1

documentation for the commands module狀態,當你運行getstatusoutput(cmd)

cmd實際運行爲{ cmd ; } 2>&1

這應該解釋; } 2>&1來自哪裏。

我的第一個猜測是,這個問題是由不剝離掉換行每次從文件中讀取行的末尾引起的,所以你實際運行的命令是一樣的東西

{ ls -l somedir 
; } 2>&1 

但是,我不知道shell編程的好壞,所以我不知道sh將如何處理分成兩行的{ ... }的內容,也不知道爲什麼現在有兩行報告第1行的問題。

第二種猜測是,有一個在你的文件中的空行,在這種情況下sh可抱怨的,因爲它尋找一個論據ls,並且找到; } 2>&1代替。

第三個猜測是其中一個文件包含},或者可能是;後跟}

最終,我不能肯定地說沒有看到文件a.txt的內容是什麼問題。

順便說一句,我希望這個文件不包含一行/ && sudo rm -rf /,因爲這可能會導致你一個或兩個問題。

1

從別的地方得到這樣的回答:

當您通過一個文件作爲一個迭代循環,換行不可剝離。以下是您的腳本正在執行的內容。事實上,你的打印語句中有一個尾隨的逗號(和你的輸出中的換行符)就是贈品。

ls -l dummyFile \n 

哪些命令解釋爲

{ ls -l dummyFile 
; } 2>&1 

呼叫line.rstrip()(或只是條)進行修復。

cmd = 'ls -l ' + line.strip() 
相關問題