【问题标题】:write text files in pythran fails在 pythran 中写入文本文件失败
【发布时间】:2021-04-09 19:38:46
【问题描述】:

我正在使用 pythran,一个 Python 到 c++ 的编译器 http://pythran.readthedocs.io/

在其手册页中,pythran says it supports the method write from TextIOWrapper

但是,试图编译这个简单的文件

文件:mylib.py

#pythran export write_test(str,bool)
#pythran export fake_write(str)

def write_test(fname,r):
    if r:
        print('writing %s'%fname)
        f = open(fname,'w')
        #write_line = f.writelines
        write_line = f.write
    else:
        print('NO FILE WILL BE WRITTEN')
        write_line = fake_write
    for i in range(10):
        write_line(str(i) + '\n')
    if r:
        f.close()

def fake_write(s):
    return 0

使用命令行

pythran mylib.py -o mylib.so -O3 -march=native -v

消息失败:

mylib.py:9:21 错误:此对象的不支持属性“写入”

Pythran 版本:0.9.8.post2

Python 版本:3.8.5

使用 Ubuntu 20.04.1 LTS

【问题讨论】:

    标签: python io write pythran


    【解决方案1】:

    当前版本的 pythran 似乎存在错误。它已在 pythran (0.9.9.dev) 的开发版本中修复。

    我们可以不使用指向f.write 函数的指针,而是定义一个没有返回的lambda 来完成这项工作并解决问题:

    #pythran export write_test(str,bool)
    #pythran export fake_write(str)
    
    def write_test(fname,r):
        if r:
            print('writing %s'%fname)
            f = open(fname,'w')
            #write_line = f.writelines
            write_line = lambda s: f.write(s)
        else:
            print('NO FILE WILL BE WRITTEN')
            write_line = fake_write
        for i in range(10):
            write_line(str(i) + '\n')
        if r:
            f.close()
    
    def fake_write(s):
        return None
    

    开发人员在其github bug report page 中建议了此修改。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2015-02-05
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2012-11-19
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多