Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/python/353.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181

Warning: file_get_contents(/data/phpspider/zhask/data//catemap/7/python-2.7/5.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
在Python脚本中使用py_compile.compile()_Python_Python 2.7 - Fatal编程技术网

在Python脚本中使用py_compile.compile()

在Python脚本中使用py_compile.compile(),python,python-2.7,Python,Python 2.7,我在努力理解 我的Python脚本生成的Python代码运行时间要晚得多,所以我现在想检查生成的代码是否有效 文件上写着py_compile.compile(文件[,cfile[,dfile[,doraise]])和 如果doraise为true,则在编译文件时遇到错误时会引发PyCompileError 所以,我试过了 source = open(generatedScriptPath, 'rt').read() + '\n' try: import py_compile x

我在努力理解

我的Python脚本生成的Python代码运行时间要晚得多,所以我现在想检查生成的代码是否有效

文件上写着
py_compile.compile(文件[,cfile[,dfile[,doraise]])

如果doraise为true,则在编译文件时遇到错误时会引发PyCompileError

所以,我试过了

source = open(generatedScriptPath, 'rt').read() + '\n'

try:
    import py_compile
    x = py_compile.compile(source, '', '', True)

except py_compile.PyCompileError, e:
    print str(e)
但不会命中内部异常,而是捕获外部异常:

回溯(最近一次调用上次):文件
“H:/code/testgen/testgen.py”,第293行,在
x=py_compile.compile(源代码,'','',True)文件“C:\Python27\lib\py_compile.py”,第106行,在compile中
将open(file,'U')作为f:IOError:[Errno 2]没有这样的文件或目录:'#此脚本是自动生成的。。。

我怎样才能解决这个问题?请注意,我对其他选择持开放态度,我只想问最简单的方法。“我刚才生成的代码在语法上是否有效?”

阅读错误消息:“没有这样的文件或目录”。第一个参数应该是要打开的文件名。或者阅读文档:“源代码是从文件名/file/”加载的。您可能更喜欢“compile”内置代码,它可以编译Python字符串。

谢谢。我刚刚从S.O.那里复制了一些其他代码。我很惊讶它竟然这么做了。无论如何,它现在可以编译了,但不会对无效代码抛出异常。您希望我更新这个问题,还是开始一个新问题?