相关疑难解决方法(0)

python 2.7/exec /有什么问题?

我有这个代码在Python 2.5中运行良好,但在2.7中没有:

import sys
import traceback
try:
    from io import StringIO
except:
    from StringIO import StringIO

def CaptureExec(stmt):
    oldio = (sys.stdin, sys.stdout, sys.stderr)
    sio = StringIO()
    sys.stdout = sys.stderr = sio
    try:
        exec(stmt, globals(), globals())
        out = sio.getvalue()
    except Exception, e:
        out = str(e) + "\n" + traceback.format_exc()
    sys.stdin, sys.stdout, sys.stderr = oldio
    return out

print "%s" % CaptureExec("""
import random
print "hello world"
""")
Run Code Online (Sandbox Code Playgroud)

我得到:

string argument expected, got 'str'
Traceback (most recent call last):
  File "D:\3.py", line 13, …

python redirect exec stdio stringio

5
推荐指数
1
解决办法
4986
查看次数

Python字符串编码和==

我在使用python中的字符串时遇到了一些问题,而==我认为它们应该是这样,而且我认为它与编码方式有关.基本上,我解析了存储在zip存档中的一些以逗号分隔的值(特别是GTFS提要,对于那些好奇的人).

我在python中使用ZipFile模块打开zip存档的某些文件,然后将其中的文本与一些已知值进行比较.这是一个示例文件:

agency_id,agency_name,agency_url,agency_phone,agency_timezone,agency_lang
ARLC,Arlington Transit,http://www.arlingtontransit.com,703-228-7433,America/New_York,en
Run Code Online (Sandbox Code Playgroud)

我正在使用的代码是尝试在文本的第一行中识别字符串"agency_id"的位置,以便我可以在任何后续行中使用相应的值.这是代码的片段:

zipped_feed = ZipFile(feed_name, "r")
agency_file = zipped_feed.open("agency.txt", "r")

line_num = 0
agencyline = agency_file.readline()
while agencyline:
    if line_num == 0:
        # this is the header, all we care about is the agency_id
        lineparts = agencyline.split(",")
        position = -1
        counter = 0
        for part in lineparts:
            part = part.strip()
            if part == "agency_id":
                position = counter              
        counter += 1
        line_num += 1
        agencyline = agency_file.readline()
    else:
        .....
Run Code Online (Sandbox Code Playgroud)

此代码适用于某些zip存档,但不适用于其他zip存档.我做了一些研究,并尝试打印repr(部分),我得到'\ xef\xbb\xbfagency_id'而不是'agency_id'.有谁知道这里发生了什么以及我如何解决它?感谢您的帮助!

python string utf-8

1
推荐指数
1
解决办法
252
查看次数

标签 统计

python ×2

exec ×1

redirect ×1

stdio ×1

string ×1

stringio ×1

utf-8 ×1