0

Python is seeing some problem with how I am opening a file with the code below

if __name__ == "__main__":
    fileName = sys.argv[1]
    with open(fileName, 'r') as f:
       for line in f:
           print line

It is producing the error

./search.py: line 3: syntax error near unexpected token `('
./search.py: line 3: `  with open(fileName, 'r') as f:'

Am I missing an import? What could be the cause of this?

EDIT: OS - CentOS, Python version 2.6.6

Not sure how I installed, I am running an image from a .edu openstack site. Not sure of the distribution, binaries, ...

4

3 回答 3

3

您必须添加import sys才能使用sys.argv. 看看这个

我试过这个:

chmod u+x yourfile.py
./yourfile.py

它给了我:

./jd.py: line 4: syntax error near unexpected token `('
./jd.py: line 4: `    with open(fileName, 'r') as f:'

如果您正在这样做./search.py file,请在文件的开头添加#!/usr/bin/env python。否则,使用python file.py input

于 2014-04-04T00:27:21.350 回答
2

问题是你根本没有用 Python 运行你的程序!当您这样做时./script(假设这script是一个文本脚本,而不是二进制程序),系统将在文件顶部查找以序列开头的行#!。如果找到该行,则该行的其余部分将用作该脚本的解释器:运行该脚本的程序。如果没有找到该行,则系统默认为/bin/sh.

因此,基本上,通过省略#!/usr/bin/python脚本顶部的魔法线,系统将使用 运行您的 Python 脚本sh,这将产生各种不正确的结果。

因此,解决方案是将这一行#!/usr/bin/python(或等效的行,如#!/usr/bin/env python)添加到 Python 脚本的顶部,以便您的系统使用 Python 运行它。或者,您也可以始终使用python search.py,而不是使用 来运行您的程序./search.py

(请注意,在 Linux 上,像这样的文件扩展名.py对系统几乎没有任何意义。因此,即使它以 . 结尾.py,Linux 也会像您写的一样执行它/bin/sh search.py)。

于 2014-04-04T00:37:31.717 回答
0

任何一个:

  1. search.py​​ 的第一行应该是 #! 注释指定查找 python 可执行文件的路径,通常是 [#!/usr/bin/env python](为什么人们在 Python 脚本的第一行写 #!/usr/bin/env python? on-the-first -line-of-a-python-script)。通常这是 #!/usr/env/bin python 。不要使用硬路径,例如 #/opt/local/bin/python2.7

  2. 否则你可以调用为python yourfile.py <yourargs> ...


以前: 如果import sys失败,请发布更多您的文件。

也许你的安装搞砸了。

您能否成功导入其他内容,例如import re

您的平台、操作系统和 Python 版本是什么?你是怎么安装的?资源?二进制文件?分配?哪些,从哪里来?

于 2014-04-04T00:31:22.460 回答