RPython sys 方法无法使用
我有以下这段代码:
import sys
def entry_point(argv):
sys.exit(1)
return 0
def target(*args):
return entry_point, None
但是,当我运行 python ./pypy/pypy/translator/goal/translate.py t.py
时,出现了以下错误:
...
[translation:ERROR] Exception: unexpected prebuilt constant: <built-in function exit>
[translation:ERROR] Processing block:
[translation:ERROR] block@9 is a <class 'pypy.objspace.flow.flowcontext.SpamBlock'>
[translation:ERROR] in (t:3)entry_point
[translation:ERROR] containing the following operations:
[translation:ERROR] v0 = simple_call((builtin_function_or_method exit), (1))
[translation:ERROR] --end--
其实错误信息还有更多内容,但我觉得最后这一部分比较重要。如果你觉得其他部分也可能有帮助,请留言,我会进行修改。
实际上,当我把 sys.exit 换成更简单的东西,比如 sys.stdout.write 时,我又遇到了另一个错误。
import sys
def entry_point(argv):
sys.stdout.write('some mesg\n')
return 0
def target(*args):
return entry_point, None
这给我带来了:
...
[translation:ERROR] AnnotatorError: annotation of v0 degenerated to SomeObject()
[translation:ERROR] v0 = getattr((module sys), ('stdout'))
[translation:ERROR]
[translation:ERROR] In <FunctionGraph of (t:3)entry_point at 0x10d03de10>:
[translation:ERROR] Happened at file t.py line 4
[translation:ERROR]
[translation:ERROR] ==> sys.stdout.write('some mesg\n')
[translation:ERROR]
[translation:ERROR] Previous annotation:
[translation:ERROR] (none)
[translation:ERROR] Processing block:
[translation:ERROR] block@3 is a <class 'pypy.objspace.flow.flowcontext.SpamBlock'>
[translation:ERROR] in (t:3)entry_point
[translation:ERROR] containing the following operations:
[translation:ERROR] v0 = getattr((module sys), ('stdout'))
[translation:ERROR] v1 = getattr(v0, ('write'))
[translation:ERROR] v2 = simple_call(v1, ('some mesg\n'))
[translation:ERROR] --end--
在 RPython 中,sys 方法是不是根本不能用?我觉得这有点奇怪,因为在 C 语言中,exit 和 stdout 是很常见的。不过,错误信息看起来可能是关于不同的问题,所以我可能是在错误的方向上努力。
目前我正在使用 这个指南来大致了解在 RPython 中什么是允许的,什么是不允许的。还有其他比较容易找到的参考资料可以让我获取更多信息吗?
1 个回答
8
sys模块不是RPython,所以你不能在RPython程序中使用它。要返回一个状态码,你必须直接从入口函数(entry_point)返回这个状态码。
另外,你也不能使用sys.stdout、sys.stdin和sys.stderr,你需要使用os.read和os.write函数,并结合文件描述符来进行读写操作。