2012-09-14 32 views
0

我用如下语句之前以下,但是当我尝试使用类似它返回一个错误的东西....Python语法错误...不知道为什么

File "test.py", line 73 
    with open(hostsTxt, 'a+') as f1, open(hostsCSV,'a+') as f2, open(hostNameLook, 'a+') as f3, open(webHostsTxt,'a+') as f4: 
      ^
SyntaxError: invalid syntax 

语法上面一行:

if hostName != "*" and hostIP != "*": 
    with open(hostsTxt, 'a+') as f1, open(hostsCSV,'a+') as f2, open(hostNameLook, 'a+') as f3, open(webHostsTxt,'a+') as f4: 

任何想法都会受到欢迎。

+0

它也可能是错位的缩进,或者您忘记使用制表符而不是空格。 – squiguy

+2

你可以提供更多的上下文? – pR0Ps

+0

@squiguy:那*通常会导致一个'IndentationError'。 –

回答

0

我关于Python 2.4和2.7都尝试它似乎是在2.4发生同样的错误,并且不会在2.7

Python 2.4中 - 我没有得到你得到了确切的同样的错误。

Python 2.4.3 (#1, Nov 3 2010, 12:52:40) 
[GCC 4.1.2 20080704 (Red Hat 4.1.2-48)] on linux2 
Type "help", "copyright", "credits" or "license" for more information. 
>>> if hostName != "*" and hostIP != "*": 
... with open(hostsTxt, 'a+') as f1, open(hostsCSV,'a+') as f2, open(hostNameLook, 'a+') as f3, open(webHostsTxt,'a+') as f4: 
    File "<stdin>", line 2 
    with open(hostsTxt, 'a+') as f1, open(hostsCSV,'a+') as f2, open(hostNameLook, 'a+') as f3, open(webHostsTxt,'a+') as f4: 
      ^
SyntaxError: invalid syntax 

的Python 2.7

Launching python -O 
Python 2.7.2 (default, Apr 17 2012, 22:01:25) 
[GCC 4.1.2 20080704 (Red Hat 4.1.2-48)] on linux2 
Type "help", "copyright", "credits" or "license" for more information. 
>>> hostIP ='localhost' 
>>> hostName = 'abcd' 
>>> if hostName != "*" and hostIP != "*": 
... with open(hostsTxt, 'a+') as f1, open(hostsCSV,'a+') as f2, open(hostNameLook, 'a+') as f3, open(webHostsTxt,'a+') as f4: 
...  print 'testing' 
... 
Traceback (most recent call last): 
    File "<stdin>", line 2, in <module> 
NameError: name 'hostsTxt' is not defined 

据我所知,你想用它不支持Python 2.4中打开即可使用。

+0

我认为这可能是......系统上有两个python实例(一个可能是2.4,但不是2.7)。而我通常使用的实例包装在py2.7中。我会在工作中测试这个 – MHibbin

+0

是的,这是问题!非常感谢。将来测试时我将不得不记住这一点 – MHibbin

7

之前的行吧,会有一个括号或括号缺失。

那么,或者你有一个根本不支持with的python版本,直到python 2.6才引入该语法。

+0

这是行前(上面的编辑)上下文与行之前...我已经上下查看脚本,我没有使用双空格的选项卡,并检查了括号和括号以及... – MHibbin

+0

用'python -tt scriptname.py'测试缩进。这条线没有任何明显的表现,可能在此之前。 –

+0

真的,1格缩进? –

相关问题