本文整理汇总了Python中compileall.compile_dir方法的典型用法代码示例。如果您正苦于以下问题:Python compileall.compile_dir方法的具体用法?Python compileall.compile_dir怎么用?Python compileall.compile_dir使用的例子?那么恭喜您, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在类compileall
的用法示例。
在下文中一共展示了compileall.compile_dir方法的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。
示例1: test_compile_files
# 需要导入模块: import compileall [as 别名]
# 或者: from compileall import compile_dir [as 别名]
def test_compile_files(self):
# Test compiling a single file, and complete directory
for fn in (self.bc_path, self.bc_path2):
try:
os.unlink(fn)
except:
pass
compileall.compile_file(self.source_path, force=False, quiet=True)
self.assertTrue(os.path.isfile(self.bc_path) \
and not os.path.isfile(self.bc_path2))
os.unlink(self.bc_path)
compileall.compile_dir(self.directory, force=False, quiet=True)
self.assertTrue(os.path.isfile(self.bc_path) \
and os.path.isfile(self.bc_path2))
os.unlink(self.bc_path)
os.unlink(self.bc_path2)
示例2: zipdir
# 需要导入模块: import compileall [as 别名]
# 或者: from compileall import compile_dir [as 别名]
def zipdir(source_root, data_paths, options):
source_root = os.path.normpath(source_root)
compileall.compile_dir(source_root, ddir='', quiet=True)
prefix = source_root + '/'
b = cStringIO.StringIO()
z = zipfile.ZipFile(b, 'w', zipfile.ZIP_DEFLATED)
for root, dirs, files in os.walk(source_root):
for f in sorted(files):
if f.endswith(('.py', '.pyc', '.pyo', '.so')):
if options.strip and f.endswith('.py'):
continue
realpath = os.path.join(root, f)
arcpath = realpath.replace(prefix, '')
log('deflate %s -> %s', realpath, arcpath)
z.write(realpath, arcpath)
for data_path in sorted(data_paths):
realpath = os.path.normpath(data_path)
arcpath = realpath.replace(prefix, '')
log('deflate %s -> %s', realpath, arcpath)
z.write(realpath, arcpath)
z.close()
return b.getvalue()
示例3: make_pyc
# 需要导入模块: import compileall [as 别名]
# 或者: from compileall import compile_dir [as 别名]
def make_pyc(self): # pylint: disable=inconsistent-return-statements
"""Create a .pyc file, and return the relative path to it."""
if env.JYTHON:
self.skipTest("Can't make .pyc files on Jython")
self.make_file("compiled.py", """\
def doit():
print("I am here!")
doit()
""")
compileall.compile_dir(".", quiet=True)
os.remove("compiled.py")
# Find the .pyc file!
for there, _, files in os.walk("."): # pragma: part covered
for f in files:
if f.endswith(".pyc"): # pragma: part covered
return os.path.join(there, f)
示例4: cmake_install
# 需要导入模块: import compileall [as 别名]
# 或者: from compileall import compile_dir [as 别名]
def cmake_install(self):
source_dir = path.dirname(path.realpath(__file__))
build_dir = get_build_dir(self.distribution)
cmake_cmd = ["cmake", source_dir]
cmake_cmd.extend(process_opts(cmake_opts))
# CMake has to be called here to update PYTHON_INSTALL_PATH
# if build and install were called separately by the user
if subprocess.call(cmake_cmd, cwd=build_dir) != 0:
raise EnvironmentError("error calling cmake")
if subprocess.call(["cmake", "--build", ".",
"--config", cmake_build_type[0],
"--target", "install"],
cwd=build_dir) != 0:
raise EnvironmentError("error installing")
import compileall
compileall.compile_dir(path.join(self.install_platlib, "symengine"))
示例5: test_compile_files
# 需要导入模块: import compileall [as 别名]
# 或者: from compileall import compile_dir [as 别名]
def test_compile_files(self):
# Test compiling a single file, and complete directory
for fn in (self.bc_path, self.bc_path2):
try:
os.unlink(fn)
except:
pass
compileall.compile_file(self.source_path, force=False, quiet=True)
self.assertTrue(os.path.isfile(self.bc_path) and
not os.path.isfile(self.bc_path2))
os.unlink(self.bc_path)
compileall.compile_dir(self.directory, force=False, quiet=True)
self.assertTrue(os.path.isfile(self.bc_path) and
os.path.isfile(self.bc_path2))
os.unlink(self.bc_path)
os.unlink(self.bc_path2)
示例6: compile_python
# 需要导入模块: import compileall [as 别名]
# 或者: from compileall import compile_dir [as 别名]
def compile_python(base_path: str) -> None:
import compileall
import py_compile
try:
num_workers = max(1, os.cpu_count() or 1)
except Exception:
num_workers = 1
for root, dirs, files in os.walk(base_path):
for f in files:
if f.rpartition('.')[-1] in ('pyc', 'pyo'):
os.remove(os.path.join(root, f))
def c(base_path: str, **kw: object) -> None:
try:
kw['invalidation_mode'] = py_compile.PycInvalidationMode.UNCHECKED_HASH
except AttributeError:
pass
compileall.compile_dir(base_path, **kw) # type: ignore
for optimize in (0, 1, 2):
c(base_path, ddir='', force=True, optimize=optimize, quiet=1, workers=num_workers)
示例7: make_pyc
# 需要导入模块: import compileall [as 别名]
# 或者: from compileall import compile_dir [as 别名]
def make_pyc(self): # pylint: disable=inconsistent-return-statements
"""Create a .pyc file, and return the path to it."""
if env.JYTHON:
self.skipTest("Can't make .pyc files on Jython")
self.make_file("compiled.py", """\
def doit():
print("I am here!")
doit()
""")
compileall.compile_dir(".", quiet=True)
os.remove("compiled.py")
# Find the .pyc file!
roots = ["."]
prefix = getattr(sys, "pycache_prefix", None)
if prefix:
roots.append(prefix)
for root in roots: # pragma: part covered
for there, _, files in os.walk(root): # pragma: part covered
for fname in files:
if fnmatch.fnmatch(fname, "compiled*.pyc"):
return os.path.join(there, fname)
示例8: doItConsolicious
# 需要导入模块: import compileall [as 别名]
# 或者: from compileall import compile_dir [as 别名]
def doItConsolicious(opt):
# reclaim stdout/stderr from log
sys.stdout = sys.__stdout__
sys.stderr = sys.__stderr__
if opt['zipfile']:
print 'Unpacking documentation...'
for n in zipstream.unzipIter(opt['zipfile'], opt['ziptargetdir']):
if n % 100 == 0:
print n,
if n % 1000 == 0:
print
print 'Done unpacking.'
if opt['compiledir']:
print 'Compiling to pyc...'
import compileall
compileall.compile_dir(opt["compiledir"])
print 'Done compiling.'
示例9: zipup_extra
# 需要导入模块: import compileall [as 别名]
# 或者: from compileall import compile_dir [as 别名]
def zipup_extra(pwd): # {{{1
info('Zipping up standard library.')
install_py4a(pwd)
root = os.path.join(cfg.dest, "python-ext")
# copy files done in Makefile's build_copy section.
def rename_pyo_pyc(fname):
# import pdb; pdb.set_trace()
fdest = os.path.splitext(fname)[0] + ".pyc"
if os.path.isfile(fdest):
os.remove(fdest)
shutil.copy2(fname, fdest)
compileall.compile_dir(root, quiet=True)
map(rename_pyo_pyc, find(root, ".pyo")[0])
zipup('python_extras%s.zip' % VERSION["extra"],
root, root,
exclude=["*.exe", "*.py", "*.pyo"])
示例10: handle
# 需要导入模块: import compileall [as 别名]
# 或者: from compileall import compile_dir [as 别名]
def handle(self, que_only=False, **options):
if que_only:
target_folders = [self._path(self.PROJECT_DIR, i) for i in ('envs', 'core', 'que')]
else:
target_folders = [self.PROJECT_DIR]
quiet = int(int(options.get('verbosity', self.default_verbosity)) <= self.default_verbosity)
for folder in target_folders:
self.display('Byte-compiling all modules in %s' % folder, color='white')
rc = compile_dir(folder, maxlevels=20, quiet=quiet)
if rc:
self.display('Byte-compiled all modules in %s' % folder, color='green')
else:
self.display('Error while byte-compiling some modules in %s' % folder, color='yellow')
示例11: recreation_check
# 需要导入模块: import compileall [as 别名]
# 或者: from compileall import compile_dir [as 别名]
def recreation_check(self, metadata):
"""Check that compileall recreates bytecode when the new metadata is
used."""
py_compile.compile(self.source_path)
self.assertEqual(*self.data())
with open(self.bc_path, 'rb') as file:
bc = file.read()[len(metadata):]
with open(self.bc_path, 'wb') as file:
file.write(metadata)
file.write(bc)
self.assertNotEqual(*self.data())
compileall.compile_dir(self.directory, force=False, quiet=True)
self.assertTrue(*self.data())
示例12: compile_program
# 需要导入模块: import compileall [as 别名]
# 或者: from compileall import compile_dir [as 别名]
def compile_program(self):
"""
Compiles the program.
"""
for location in self.input_location:
compileall.compile_dir(location, quiet=True)
self.create_program(skip_rebuild=True)
示例13: recreation_check
# 需要导入模块: import compileall [as 别名]
# 或者: from compileall import compile_dir [as 别名]
def recreation_check(self, metadata):
"""Check that compileall recreates bytecode when the new metadata is
used."""
if not hasattr(os, 'stat'):
return
py_compile.compile(self.source_path)
self.assertEqual(*self.data())
with open(self.bc_path, 'rb') as file:
bc = file.read()[len(metadata):]
with open(self.bc_path, 'wb') as file:
file.write(metadata)
file.write(bc)
self.assertNotEqual(*self.data())
compileall.compile_dir(self.directory, force=False, quiet=True)
self.assertTrue(*self.data())
示例14: test_freshPyReplacesStalePyc
# 需要导入模块: import compileall [as 别名]
# 或者: from compileall import compile_dir [as 别名]
def test_freshPyReplacesStalePyc(self):
"""
Verify that if a stale .pyc file on the PYTHONPATH is replaced by a
fresh .py file, the plugins in the new .py are picked up rather than
the stale .pyc, even if the .pyc is still around.
"""
mypath = self.appPackage.child("stale.py")
mypath.setContent(pluginFileContents('one'))
# Make it super stale
x = time.time() - 1000
os.utime(mypath.path, (x, x))
pyc = mypath.sibling('stale.pyc')
# compile it
if _PY3:
# On python 3, don't use the __pycache__ directory; the intention
# of scanning for .pyc files is for configurations where you want
# to intentionally include them, which means we _don't_ scan for
# them inside cache directories.
extra = dict(legacy=True)
else:
# On python 2 this option doesn't exist.
extra = dict()
compileall.compile_dir(self.appPackage.path, quiet=1, **extra)
os.utime(pyc.path, (x, x))
# Eliminate the other option.
mypath.remove()
# Make sure it's the .pyc path getting cached.
self.resetEnvironment()
# Sanity check.
self.assertIn('one', self.getAllPlugins())
self.failIfIn('two', self.getAllPlugins())
self.resetEnvironment()
mypath.setContent(pluginFileContents('two'))
self.failIfIn('one', self.getAllPlugins())
self.assertIn('two', self.getAllPlugins())
示例15: test_alwaysPreferPy
# 需要导入模块: import compileall [as 别名]
# 或者: from compileall import compile_dir [as 别名]
def test_alwaysPreferPy(self):
"""
Verify that .py files will always be preferred to .pyc files, regardless of
directory listing order.
"""
mypath = FilePath(self.mktemp())
mypath.createDirectory()
pp = modules.PythonPath(sysPath=[mypath.path])
originalSmartPath = pp._smartPath
def _evilSmartPath(pathName):
o = originalSmartPath(pathName)
originalChildren = o.children
def evilChildren():
# normally this order is random; let's make sure it always
# comes up .pyc-first.
x = list(originalChildren())
x.sort()
x.reverse()
return x
o.children = evilChildren
return o
mypath.child("abcd.py").setContent(b'\n')
compileall.compile_dir(mypath.path, quiet=True)
# sanity check
self.assertEqual(len(list(mypath.children())), 2)
pp._smartPath = _evilSmartPath
self.assertEqual(pp['abcd'].filePath,
mypath.child('abcd.py'))