我们从Python开源项目中,提取了以下33个代码示例,用于说明如何使用py_compile.PyCompileError()。
def _get_codename(self, pathname, basename): """Return (filename, archivename) for the path. Given a module name path, return the correct file path and archive name, compiling if necessary. For example, given /python/lib/string, return (/python/lib/string.pyc, string). """ file_py = pathname + ".py" file_pyc = pathname + ".pyc" file_pyo = pathname + ".pyo" if os.path.isfile(file_pyo) and \ os.stat(file_pyo).st_mtime >= os.stat(file_py).st_mtime: fname = file_pyo # Use .pyo file elif not os.path.isfile(file_pyc) or \ os.stat(file_pyc).st_mtime < os.stat(file_py).st_mtime: import py_compile if self.debug: print "Compiling", file_py try: py_compile.compile(file_py, file_pyc, None, True) except py_compile.PyCompileError,err: print err.msg fname = file_pyc else: fname = file_pyc archivename = os.path.split(fname)[1] if basename: archivename = "%s/%s" % (basename, archivename) return (fname, archivename)
def copy_to_layout(target, rel_sources): count = 0 if target.suffix.lower() == '.zip': if target.exists(): target.unlink() with ZipFile(str(target), 'w', ZIP_DEFLATED) as f: with tempfile.TemporaryDirectory() as tmpdir: for s, rel in rel_sources: if rel.suffix.lower() == '.py': pyc = Path(tmpdir) / rel.with_suffix('.pyc').name try: py_compile.compile(str(s), str(pyc), str(rel), doraise=True, optimize=2) except py_compile.PyCompileError: f.write(str(s), str(rel)) else: f.write(str(pyc), str(rel.with_suffix('.pyc'))) else: f.write(str(s), str(rel)) count += 1 else: for s, rel in rel_sources: dest = target / rel try: dest.parent.mkdir(parents=True) except FileExistsError: pass if dest.is_file(): dest.chmod(stat.S_IWRITE) shutil.copy(str(s), str(dest)) if dest.is_file(): dest.chmod(stat.S_IWRITE) count += 1 return count
def _get_codename(self, pathname, basename): """Return (filename, archivename) for the path. Given a module name path, return the correct file path and archive name, compiling if necessary. For example, given /python/lib/string, return (/python/lib/string.pyc, string). """ file_py = pathname + ".py" file_pyc = pathname + ".pyc" file_pyo = pathname + ".pyo" if os.path.isfile(file_pyo) and \ os.stat(file_pyo).st_mtime >= os.stat(file_py).st_mtime: fname = file_pyo # Use .pyo file elif not os.path.isfile(file_pyc) or \ os.stat(file_pyc).st_mtime < os.stat(file_py).st_mtime: import py_compile if self.debug: print("Compiling", file_py) try: py_compile.compile(file_py, file_pyc, None, True) except py_compile.PyCompileError as err: print(err.msg) fname = file_pyc else: fname = file_pyc archivename = os.path.split(fname)[1] if basename: archivename = "%s/%s" % (basename, archivename) return (fname, archivename)
def syntax_check(filename): """ Run python's compiler over the file, and discard the results. Arrange to generate an exception if the file does not compile. This is needed because distutil's own use of pycompile (in the distutils.utils module) is broken, and doesn't stop on error. """ try: tmpfd, tmp_file = tempfile.mkstemp() py_compile.compile(filename, tmp_file, doraise=True) except py_compile.PyCompileError as e: res = "" for err in e.exc_value: if isinstance(err, six.string_types): res += err + "\n" continue # Assume it's a tuple of (filename, lineno, col, code) fname, line, col, code = err res += "line {0:d}, column {1}, in {2}:\n{3}".format( line, col or "unknown", fname, code) raise DistutilsError(res) finally: os.remove(tmp_file) # On Solaris, ld inserts the full argument to the -o option into the symbol # table. This means that the resulting object will be different depending on # the path at which the workspace lives, and not just on the interesting content # of the object. # # In order to work around that bug (7076871), we create a new compiler class # that looks at the argument indicating the output file, chdirs to its # directory, and runs the real link with the output file set to just the base # name of the file. # # Unfortunately, distutils isn't too customizable in this regard, so we have to # twiddle with a couple of the names in the distutils.ccompiler namespace: we # have to add a new entry to the compiler_class dict, and we have to override # the new_compiler() function to point to our own. Luckily, our copy of # new_compiler() gets to be very simple, since we always know what we want to # return.
def compile_file(fullname, ddir=None, force=0, rx=None, quiet=0): """Byte-compile one file. Arguments (only fullname is required): fullname: the file to byte-compile ddir: if given, purported directory name (this is the directory name that will show up in error messages) force: if 1, force compilation, even if timestamps are up-to-date quiet: if 1, be quiet during compilation """ success = 1 name = os.path.basename(fullname) if ddir is not None: dfile = os.path.join(ddir, name) else: dfile = None if rx is not None: mo = rx.search(fullname) if mo: return success if os.path.isfile(fullname): head, tail = name[:-3], name[-3:] if tail == '.py': if not force: try: mtime = int(os.stat(fullname).st_mtime) expect = struct.pack('<4sl', imp.get_magic(), mtime) cfile = fullname + (__debug__ and 'c' or 'o') with open(cfile, 'rb') as chandle: actual = chandle.read(8) if expect == actual: return success except IOError: pass if not quiet: print 'Compiling', fullname, '...' try: ok = py_compile.compile(fullname, None, dfile, True) except py_compile.PyCompileError,err: if quiet: print 'Compiling', fullname, '...' print err.msg success = 0 except IOError, e: print "Sorry", e success = 0 else: if ok == 0: success = 0 return success
def compile_file(fullname, ddir=None, force=0, rx=None, quiet=0): """Byte-compile one file. Arguments (only fullname is required): fullname: the file to byte-compile ddir: if given, the directory name compiled in to the byte-code file. force: if 1, force compilation, even if timestamps are up-to-date quiet: if 1, be quiet during compilation """ success = 1 name = os.path.basename(fullname) if ddir is not None: dfile = os.path.join(ddir, name) else: dfile = None if rx is not None: mo = rx.search(fullname) if mo: return success if os.path.isfile(fullname): head, tail = name[:-3], name[-3:] if tail == '.py': if not force: try: mtime = int(os.stat(fullname).st_mtime) expect = struct.pack('<4sl', imp.get_magic(), mtime) cfile = fullname + (__debug__ and 'c' or 'o') with open(cfile, 'rb') as chandle: actual = chandle.read(8) if expect == actual: return success except IOError: pass if not quiet: print 'Compiling', fullname, '...' try: ok = py_compile.compile(fullname, None, dfile, True) except py_compile.PyCompileError,err: if quiet: print 'Compiling', fullname, '...' print err.msg success = 0 except IOError, e: print "Sorry", e success = 0 else: if ok == 0: success = 0 return success
def compile_file(fullname, ddir=None, force=0, rx=None, quiet=0): """Byte-compile one file. Arguments (only fullname is required): fullname: the file to byte-compile ddir: if given, the directory name compiled in to the byte-code file. force: if 1, force compilation, even if timestamps are up-to-date quiet: if 1, be quiet during compilation """ success = 1 name = os.path.basename(fullname) if ddir is not None: dfile = os.path.join(ddir, name).replace(os.sep, '/') else: dfile = None if rx is not None: mo = rx.search(fullname) if mo: return success if os.path.isfile(fullname): head, tail = name[:-3], name[-3:] if tail == '.py': timeStr = subprocess.check_output( ['git', '--no-pager', 'log', '-n', '1', '--format="%ct"', '--', fullname])[1:-2] if not force: try: if not timeStr: mtime = int(os.stat(fullname).st_mtime) else: mtime = int(timeStr) expect = struct.pack('<4sl', imp.get_magic(), mtime) cfile = fullname + (__debug__ and 'c' or 'o') with open(cfile, 'rb') as chandle: actual = chandle.read(8) if expect == actual: return success except IOError: pass if not quiet: print 'Compiling', fullname, '...' try: ok = do_compile(fullname, None, dfile, True, timeStr) except py_compile.PyCompileError, err: if quiet: print 'Compiling', fullname, '...' print err.msg success = 0 except IOError, e: print "Sorry", e success = 0 else: if ok == 0: success = 0 return success
def putData(self, mibname, data, comments=[], dryRun=False): if dryRun: debug.logger & debug.flagWriter and debug.logger('dry run mode') return if not os.path.exists(self._path): try: os.makedirs(self._path) except OSError: raise error.PySmiWriterError('failure creating destination directory %s: %s' % (self._path, sys.exc_info()[1]), writer=self) if comments: data = '#\n' + ''.join(['# %s\n' % x for x in comments]) + '#\n' + data pyfile = os.path.join(self._path, decode(mibname)) + self.suffixes[imp.PY_SOURCE][0][0] try: fd, tfile = tempfile.mkstemp(dir=self._path) os.write(fd, encode(data)) os.close(fd) os.rename(tfile, pyfile) except (OSError, IOError, UnicodeEncodeError): exc = sys.exc_info() try: os.unlink(tfile) except OSError: pass raise error.PySmiWriterError('failure writing file %s: %s' % (pyfile, exc[1]), file=pyfile, writer=self) debug.logger & debug.flagWriter and debug.logger('created file %s' % pyfile) if self.pyCompile: try: if sys.version_info[0:2] > (3, 1): py_compile.compile(pyfile, doraise=True, optimize=self.pyOptimizationLevel) else: py_compile.compile(pyfile, doraise=True) except (SyntaxError, py_compile.PyCompileError): pass # XXX except: try: os.unlink(pyfile) except Exception: pass raise error.PySmiWriterError('failure compiling %s: %s' % (pyfile, sys.exc_info()[1]), file=mibname, writer=self) debug.logger & debug.flagWriter and debug.logger('%s stored' % mibname)