Appendix之setup.py:附录文件内容记录setup.py
- from __future__ import print_function
-
- from distutils.ccompiler import new_compiler as _new_compiler
- from distutils.command.clean import clean, log
- from distutils.core import Command
- from distutils.dir_util import remove_tree
- from distutils.errors import DistutilsExecError
- from distutils.msvccompiler import MSVCCompiler
- from setuptools import setup, find_packages, Extension, Distribution
- from setuptools.command.build_ext import build_ext
- from subprocess import Popen, PIPE
- import argparse
- import errno
- import os
- import platform
- import re
- import shlex
- import sys
-
- We don't need six...
- PY3 = sys.version_info[0] >= 3
-
- if PY3:
- from shlex import quote as shell_quote
- else:
- from pipes import quote as shell_quote
-
- try:
- This depends on _winreg, which is not availible on not-Windows.
- from distutils.msvc9compiler import MSVCCompiler as MSVC9Compiler
- except ImportError:
- MSVC9Compiler = None
- try:
- from distutils._msvccompiler import MSVCCompiler as MSVC14Compiler
- except ImportError:
- MSVC14Compiler = None
-
- try:
- from Cython import __version__ as cython_version
- from Cython.Build import cythonize
- except ImportError:
- cythonize = None
- else:
- We depend upon some features in Cython 0.27; reject older ones.
- if tuple(map(int, cython_version.split('.'))) < (0, 27):
- print("Cython {} is too old for PyAV; ignoring it.".format(cython_version))
- cythonize = None
-
-
- We will embed this metadata into the package so it can be recalled for debugging.
- version = open('VERSION.txt').read().strip()
- try:
- git_commit, _ = Popen(['git', 'describe', '--tags'], stdout=PIPE, stderr=PIPE).communicate()
- except OSError:
- git_commit = None
- else:
- git_commit = git_commit.decode().strip()
-
-
- _cflag_parser = argparse.ArgumentParser(add_help=False)
- _cflag_parser.add_argument('-I', dest='include_dirs', action='append')
- _cflag_parser.add_argument('-L', dest='library_dirs', action='append')
- _cflag_parser.add_argument('-l', dest='libraries', action='append')
- _cflag_parser.add_argument('-D', dest='define_macros', action='append')
- _cflag_parser.add_argument('-R', dest='runtime_library_dirs', action='append')
- def parse_cflags(raw_cflags):
- raw_args = shlex.split(raw_cflags.strip())
- args, unknown = _cflag_parser.parse_known_args(raw_args)
- config = {k: v or [] for k, v in args.__dict__.items()}
- for i, x in enumerate(config['define_macros']):
- parts = x.split('=', 1)
- value = x[1] or None if len(x) == 2 else None
- config['define_macros'][i] = (parts[0], value)
- return config, ' '.join(shell_quote(x) for x in unknown)
-
- def get_library_config(name):
- """Get distutils-compatible extension extras for the given library.
- This requires ``pkg-config``.
- """
- try:
- proc = Popen(['pkg-config', '--cflags', '--libs', name], stdout=PIPE, stderr=PIPE)
- except OSError:
- print('pkg-config is required for building PyAV')
- exit(1)
-
- raw_cflags, err = proc.communicate()
- if proc.wait():
- return
-
- known, unknown = parse_cflags(raw_cflags.decode('utf8'))
- if unknown:
- print("pkg-config returned flags we don't understand: {}".format(unknown))
- exit(1)
-
- return known
-
-
- def update_extend(dst, src):
- """Update the `dst` with the `src`, extending values where lists.
- Primiarily useful for integrating results from `get_library_config`.
- """
- for k, v in src.items():
- existing = dst.setdefault(k, [])
- for x in v:
- if x not in existing:
- existing.append(x)
-
-
- def unique_extend(a, *args):
- a[:] = list(set().union(a, *args))
-
-
- Obtain the ffmpeg dir from the "--ffmpeg-dir=<dir>" argument
- FFMPEG_DIR = None
- FFMPEG_DIR = 'D://Program Files//ffmpeg'
- for i, arg in enumerate(sys.argv):
- if arg.startswith('--ffmpeg-dir='):
- FFMPEG_DIR = arg.split('=')[1]
- break
-
- if FFMPEG_DIR is not None:
- delete the --ffmpeg-dir arg so that distutils does not see it
- del sys.argv[i]
- if not os.path.isdir(FFMPEG_DIR):
- print('The specified ffmpeg directory does not exist')
- exit(1)
- else:
- Check the environment variable FFMPEG_DIR
- FFMPEG_DIR = os.environ.get('FFMPEG_DIR')
- if FFMPEG_DIR is not None:
- if not os.path.isdir(FFMPEG_DIR):
- FFMPEG_DIR = None
-
- if FFMPEG_DIR is not None:
- ffmpeg_lib = os.path.join(FFMPEG_DIR, 'lib')
- ffmpeg_include = os.path.join(FFMPEG_DIR, 'include')
- if os.path.exists(ffmpeg_lib):
- ffmpeg_lib = [ffmpeg_lib]
- else:
- ffmpeg_lib = [FFMPEG_DIR]
- if os.path.exists(ffmpeg_include):
- ffmpeg_include = [ffmpeg_include]
- else:
- ffmpeg_include = [FFMPEG_DIR]
- else:
- ffmpeg_lib = []
- ffmpeg_include = []
-
-
- The "extras" to be supplied to every one of our modules.
- This is expanded heavily by the `config` command.
- extension_extra = {
- 'include_dirs': ['include'] + ffmpeg_include, The first are PyAV's includes.
- 'libraries' : [],
- 'library_dirs': ffmpeg_lib,
- }
-
- The macros which describe the current PyAV version.
- config_macros = {
- "PYAV_VERSION": version,
- "PYAV_VERSION_STR": '"%s"' % version,
- "PYAV_COMMIT_STR": '"%s"' % (git_commit or 'unknown-commit'),
- }
-
-
- def dump_config():
- """Print out all the config information we have so far (for debugging)."""
- print('PyAV:', version, git_commit or '(unknown commit)')
- print('Python:', sys.version.encode('unicode_escape' if PY3 else 'string-escape'))
- print('platform:', platform.platform())
- print('extension_extra:')
- for k, vs in extension_extra.items():
- print('\t%s: %s' % (k, [x.encode('utf8') for x in vs]))
- print('config_macros:')
- for x in sorted(config_macros.items()):
- print('\t%s=%s' % x)
-
-
- Monkey-patch for CCompiler to be silent.
- def _CCompiler_spawn_silent(cmd, dry_run=None):
- """Spawn a process, and eat the stdio."""
- proc = Popen(cmd, stdout=PIPE, stderr=PIPE)
- out, err = proc.communicate()
- if proc.returncode:
- raise DistutilsExecError(err)
-
- def new_compiler(*args, **kwargs):
- """Create a C compiler.
- :param bool silent: Eat all stdio? Defaults to ``True``.
- All other arguments passed to ``distutils.ccompiler.new_compiler``.
- """
- make_silent = kwargs.pop('silent', True)
- cc = _new_compiler(*args, **kwargs)
- If MSVC10, initialize the compiler here and add /MANIFEST to linker flags.
- See Python issue 4431 (https://bugs.python.org/issue4431)
- if is_msvc(cc):
- from distutils.msvc9compiler import get_build_version
- if get_build_version() == 10:
- cc.initialize()
- for ldflags in [cc.ldflags_shared, cc.ldflags_shared_debug]:
- unique_extend(ldflags, ['/MANIFEST'])
- If MSVC14, do not silence. As msvc14 requires some custom
- steps before the process is spawned, we can't monkey-patch this.
- elif get_build_version() == 14:
- make_silent = False
- monkey-patch compiler to suppress stdout and stderr.
- if make_silent:
- cc.spawn = _CCompiler_spawn_silent
- return cc
-
-
- _msvc_classes = tuple(filter(None, (MSVCCompiler, MSVC9Compiler, MSVC14Compiler)))
- def is_msvc(cc=None):
- cc = _new_compiler() if cc is None else cc
- return isinstance(cc, _msvc_classes)
-
-
- if os.name == 'nt':
-
- if is_msvc():
- config_macros['inline'] = '__inline'
-
- Since we're shipping a self contained unit on Windows, we need to mark
- the package as such. On other systems, let it be universal.
- class BinaryDistribution(-title class_ inherited__">Distribution):
- def is_pure(self):
- return False
-
- distclass = BinaryDistribution
-
- else:
-
- Nothing to see here.
- distclass = Distribution
-
-
- Monkey-patch Cython to not overwrite embedded signatures.
- if cythonize:
-
- from Cython.Compiler.AutoDocTransforms import EmbedSignature
-
- old_embed_signature = EmbedSignature._embed_signature
- def new_embed_signature(self, sig, doc):
-
- Strip any `self` parameters from the front.
- sig = re.sub(r'\(self(,\s+)?', '(', sig)
-
- If they both start with the same signature; skip it.
- if sig and doc:
- new_name = sig.split('(')[0].strip()
- old_name = doc.split('(')[0].strip()
- if new_name == old_name:
- return doc
- if new_name.
网站声明:如果转载,请联系本站管理员。否则一切后果自行承担。
加入交流群
请使用微信扫一扫!