3

我想数一数我写了多少行代码。

这是Python代码:

import os
import sys

EXT = ['.c','.cpp','.java','.py']

def main():
    l = []
    if os.path.isdir(sys.argv[1]):
        for root, dirs, files in os.walk(sys.argv[1]):
            l.extend([os.path.join(root, name) for name in files])
    else:
        l.append(sys.argv[1])

    params = ["'"+p+"'" for p in l if os.path.splitext(p)[1] in EXT]

    result = os.popen("wc -l %s "%" ".join(params)).read()
    print result

if __name__ == '__main__':
    main()

在此之前,它按预期运行。但是今天,它给了我这个错误:

sh: 1: Syntax error: Unterminated quoted string

我不知道发生了什么。

4

3 回答 3

4

您的 Python 脚本缺少shebang行。将以下内容添加到文件顶部:

#!/usr/bin/env python

然后您应该能够运行以下命令,假设您的脚本位于/path/to/your_script.py并且它设置了可执行位

/path/to/your_script.py arg1 arg2 [...]

或者:

python /path/to/your_script.py arg1 arg2 [...]

更新以下评论

我怀疑发生的变化是名称中包含 a 的源文件'已添加到您正在检查的目录中,并且 shell 对此感到窒息。

您可以将以下功能添加到您的程序中:

def shellquote(s):
    return "'" + s.replace("'", "'\\''") + "'"

[摘自Greg Hewgill如何在 Python 中转义 os.system() 调用的回答?.]

并这样称呼它:

params = [shellquote(p) for p in l if os.path.splitext(p)[1] in EXT]
于 2013-08-31T03:20:11.300 回答
1

@Johnsyweb 的更新答案似乎有正确的诊断,但正确的解决方法是不使用 shell 来调用wc. 尝试这样的事情:

cmd = ['/bin/wc', '-l'] # Need full path!
[cmd.extend(p) for p in l if os.path.splitext(p)[1] in EXT]
result = os.popen2(cmd).read()

请注意,该subprocess模块现在是推荐的解决方案。但是,切换到它需要对您当前的代码进行较少侵入性的更改;见http://docs.python.org/2/library/subprocess.html#replacing-os-popen-os-popen2-os-popen3

于 2013-08-31T07:52:17.193 回答
0

看起来您的 Python 程序被解析为 shell 脚本。在标题处添加类似这样的内容以指示您的 Python 所在的位置:

#!/usr/bin/python

或者你只是运行python a.py

于 2013-08-31T03:21:01.840 回答