SyntaxError 尝试使用 python 2.7 执行 python 3 代码 [英] SyntaxError trying to execute python 3 code with python 2.7

查看:60
本文介绍了SyntaxError 尝试使用 python 2.7 执行 python 3 代码的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在python 2.7环境下运行了python 3代码,其他代码如下,出现如下错误,请高手指点如何解决,谢谢!如果您想了解更多信息,请告诉我.

I run the python 3 code which from others code as following in the python 2.7 environment, there is error as following, please give me some hints how to solve it, thanks! If you want more information, please tell me.

python 代码:

#! /usr/bin/env python

from __future__ import print_function
import argparse
from collections import defaultdict
import numpy as np
import os
import sys
import utils


if __name__ == '__main__':
    parser = argparse.ArgumentParser()
    parser.add_argument('target')
    args = parser.parse_args()

    target = defaultdict(list)
    for i, line in enumerate(sys.stdin):
        filename, score, *rect = line.strip().split()
        name, _ = os.path.splitext(filename)
        score = float(score)
        rect = tuple(map(float, rect))
        target[name].append((score, rect))

        if (i + 1) % 1000 == 0:
            print(i + 1, file=sys.stderr)

    for name in target.keys():
        target[name] = np.array(target[name], dtype=utils.dtype)
        target[name].sort(order=('score',))
        target[name][:] = target[name][::-1]

    np.savez_compressed(args.target, **target)

错误:

File "./scripts/lo.py", line 19
    filename, score, *rect = line.strip().split()
                     ^
SyntaxError: invalid syntax

推荐答案

该脚本使用了 Python 3.0 中添加的称为扩展可迭代解包"的东西.
该功能在 PEP 3132 中进行了描述.

The script is using something called "Extended Iterable Unpacking" which was added to Python 3.0.
The feature is described in PEP 3132.

要在 Python 2 中做同样的事情,替换问题行:

To do the same thing in Python 2, replace the problem line:

    filename, score, *rect = line.strip().split()

用这两行:

    seq = line.strip().split()
    filename, score, rect = seq[0], seq[1], seq[2:]

OR 这两个:

   seq = line.strip().split()
   (filename, score), rect = seq[:2], seq[2:]

这篇关于SyntaxError 尝试使用 python 2.7 执行 python 3 代码的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆