Python中的'for key in' - 如何修复'SyntaxError: invalid syntax

1 投票
2 回答
2294 浏览
提问于 2025-04-17 16:05

我正在尝试从GitHub上安装一个Python包(使用命令python setup.py install),这个包的地址是 https://github.com/danielfullmer/nzbfs,但是遇到了问题。

SyntaxError: ('invalid syntax', ('build/bdist.linux-x86_64/egg/nzbfs/fs.py', 135, 15, "            for key in ('st_atime', 'st_ctime', 'st_gid', 'st_mode', 'st_mtime', 'st_nlink', 'st_size', 'st_uid'):\n"))

我想知道哪里出错了?我在Debian系统上试过Python 2.6和3.1,但总是在那行 for key .. 卡住了。

def getattr(self, path, fh=None):
    st = os.lstat(self.db_root + path)

    d = {
        key: getattr(st, key)
        for key in ('st_atime', 'st_ctime', 'st_gid', 'st_mode',
                    'st_mtime', 'st_nlink', 'st_size', 'st_uid')
    }

    if stat.S_ISREG(st.st_mode):
        nzf_size = get_nzf_attr(self.db_root + path, 'size')
        if nzf_size is not None:
            d['st_size'] = nzf_size
        nzf_mtime = get_nzf_attr(self.db_root + path, 'mtime')
        if nzf_mtime is not None:
            d['st_mtime'] = nzf_mtime
    d['st_blocks'] = d['st_size'] / 512

    return d                            

2 个回答

1

你可以把字典推导式改成这样

d = dict(
        (key, getattr(st, key))
        for key in ('st_atime', 'st_ctime', 'st_gid', 'st_mode',
                    'st_mtime', 'st_nlink', 'st_size', 'st_uid')
    )

如果你需要它在2.6版本中运行的话

3

出错的那一行代码叫做 字典推导式,这个功能是在 Python 2.7 和 3 版本中新增的。

这个模块 支持 Python 3;比如它使用了 ConfigParser 模块,而在 Python 3 中这个模块被改名为 configparser。所以你只能使用 Python 2.7。

如果这对你来说是个大问题,你需要去 向开发者反馈,请求他们让这个模块支持 Python 2.6(其实实现起来并不难)。

撰写回答