Appendix之setup.py:附录文件内容记录setup.py


巴山夜雨
巴山夜雨 2022-09-19 13:31:14 50940
分类专栏: 资讯

Appendix之setup.py:附录文件内容记录setup.py

附录文件内容记录setup.py

  1. from __future__ import print_function
  2. from distutils.ccompiler import new_compiler as _new_compiler
  3. from distutils.command.clean import clean, log
  4. from distutils.core import Command
  5. from distutils.dir_util import remove_tree
  6. from distutils.errors import DistutilsExecError
  7. from distutils.msvccompiler import MSVCCompiler
  8. from setuptools import setup, find_packages, Extension, Distribution
  9. from setuptools.command.build_ext import build_ext
  10. from subprocess import Popen, PIPE
  11. import argparse
  12. import errno
  13. import os
  14. import platform
  15. import re
  16. import shlex
  17. import sys
  18. We don't need six...
  19. PY3 = sys.version_info[0] >= 3
  20. if PY3:
  21. from shlex import quote as shell_quote
  22. else:
  23. from pipes import quote as shell_quote
  24. try:
  25. This depends on _winreg, which is not availible on not-Windows.
  26. from distutils.msvc9compiler import MSVCCompiler as MSVC9Compiler
  27. except ImportError:
  28. MSVC9Compiler = None
  29. try:
  30. from distutils._msvccompiler import MSVCCompiler as MSVC14Compiler
  31. except ImportError:
  32. MSVC14Compiler = None
  33. try:
  34. from Cython import __version__ as cython_version
  35. from Cython.Build import cythonize
  36. except ImportError:
  37. cythonize = None
  38. else:
  39. We depend upon some features in Cython 0.27; reject older ones.
  40. if tuple(map(int, cython_version.split('.'))) < (0, 27):
  41. print("Cython {} is too old for PyAV; ignoring it.".format(cython_version))
  42. cythonize = None
  43. We will embed this metadata into the package so it can be recalled for debugging.
  44. version = open('VERSION.txt').read().strip()
  45. try:
  46. git_commit, _ = Popen(['git', 'describe', '--tags'], stdout=PIPE, stderr=PIPE).communicate()
  47. except OSError:
  48. git_commit = None
  49. else:
  50. git_commit = git_commit.decode().strip()
  51. _cflag_parser = argparse.ArgumentParser(add_help=False)
  52. _cflag_parser.add_argument('-I', dest='include_dirs', action='append')
  53. _cflag_parser.add_argument('-L', dest='library_dirs', action='append')
  54. _cflag_parser.add_argument('-l', dest='libraries', action='append')
  55. _cflag_parser.add_argument('-D', dest='define_macros', action='append')
  56. _cflag_parser.add_argument('-R', dest='runtime_library_dirs', action='append')
  57. def parse_cflags(raw_cflags):
  58. raw_args = shlex.split(raw_cflags.strip())
  59. args, unknown = _cflag_parser.parse_known_args(raw_args)
  60. config = {k: v or [] for k, v in args.__dict__.items()}
  61. for i, x in enumerate(config['define_macros']):
  62. parts = x.split('=', 1)
  63. value = x[1] or None if len(x) == 2 else None
  64. config['define_macros'][i] = (parts[0], value)
  65. return config, ' '.join(shell_quote(x) for x in unknown)
  66. def get_library_config(name):
  67. """Get distutils-compatible extension extras for the given library.
  68. This requires ``pkg-config``.
  69. """
  70. try:
  71. proc = Popen(['pkg-config', '--cflags', '--libs', name], stdout=PIPE, stderr=PIPE)
  72. except OSError:
  73. print('pkg-config is required for building PyAV')
  74. exit(1)
  75. raw_cflags, err = proc.communicate()
  76. if proc.wait():
  77. return
  78. known, unknown = parse_cflags(raw_cflags.decode('utf8'))
  79. if unknown:
  80. print("pkg-config returned flags we don't understand: {}".format(unknown))
  81. exit(1)
  82. return known
  83. def update_extend(dst, src):
  84. """Update the `dst` with the `src`, extending values where lists.
  85. Primiarily useful for integrating results from `get_library_config`.
  86. """
  87. for k, v in src.items():
  88. existing = dst.setdefault(k, [])
  89. for x in v:
  90. if x not in existing:
  91. existing.append(x)
  92. def unique_extend(a, *args):
  93. a[:] = list(set().union(a, *args))
  94. Obtain the ffmpeg dir from the "--ffmpeg-dir=<dir>" argument
  95. FFMPEG_DIR = None
  96. FFMPEG_DIR = 'D://Program Files//ffmpeg'
  97. for i, arg in enumerate(sys.argv):
  98. if arg.startswith('--ffmpeg-dir='):
  99. FFMPEG_DIR = arg.split('=')[1]
  100. break
  101. if FFMPEG_DIR is not None:
  102. delete the --ffmpeg-dir arg so that distutils does not see it
  103. del sys.argv[i]
  104. if not os.path.isdir(FFMPEG_DIR):
  105. print('The specified ffmpeg directory does not exist')
  106. exit(1)
  107. else:
  108. Check the environment variable FFMPEG_DIR
  109. FFMPEG_DIR = os.environ.get('FFMPEG_DIR')
  110. if FFMPEG_DIR is not None:
  111. if not os.path.isdir(FFMPEG_DIR):
  112. FFMPEG_DIR = None
  113. if FFMPEG_DIR is not None:
  114. ffmpeg_lib = os.path.join(FFMPEG_DIR, 'lib')
  115. ffmpeg_include = os.path.join(FFMPEG_DIR, 'include')
  116. if os.path.exists(ffmpeg_lib):
  117. ffmpeg_lib = [ffmpeg_lib]
  118. else:
  119. ffmpeg_lib = [FFMPEG_DIR]
  120. if os.path.exists(ffmpeg_include):
  121. ffmpeg_include = [ffmpeg_include]
  122. else:
  123. ffmpeg_include = [FFMPEG_DIR]
  124. else:
  125. ffmpeg_lib = []
  126. ffmpeg_include = []
  127. The "extras" to be supplied to every one of our modules.
  128. This is expanded heavily by the `config` command.
  129. extension_extra = {
  130. 'include_dirs': ['include'] + ffmpeg_include, The first are PyAV's includes.
  131. 'libraries' : [],
  132. 'library_dirs': ffmpeg_lib,
  133. }
  134. The macros which describe the current PyAV version.
  135. config_macros = {
  136. "PYAV_VERSION": version,
  137. "PYAV_VERSION_STR": '"%s"' % version,
  138. "PYAV_COMMIT_STR": '"%s"' % (git_commit or 'unknown-commit'),
  139. }
  140. def dump_config():
  141. """Print out all the config information we have so far (for debugging)."""
  142. print('PyAV:', version, git_commit or '(unknown commit)')
  143. print('Python:', sys.version.encode('unicode_escape' if PY3 else 'string-escape'))
  144. print('platform:', platform.platform())
  145. print('extension_extra:')
  146. for k, vs in extension_extra.items():
  147. print('\t%s: %s' % (k, [x.encode('utf8') for x in vs]))
  148. print('config_macros:')
  149. for x in sorted(config_macros.items()):
  150. print('\t%s=%s' % x)
  151. Monkey-patch for CCompiler to be silent.
  152. def _CCompiler_spawn_silent(cmd, dry_run=None):
  153. """Spawn a process, and eat the stdio."""
  154. proc = Popen(cmd, stdout=PIPE, stderr=PIPE)
  155. out, err = proc.communicate()
  156. if proc.returncode:
  157. raise DistutilsExecError(err)
  158. def new_compiler(*args, **kwargs):
  159. """Create a C compiler.
  160. :param bool silent: Eat all stdio? Defaults to ``True``.
  161. All other arguments passed to ``distutils.ccompiler.new_compiler``.
  162. """
  163. make_silent = kwargs.pop('silent', True)
  164. cc = _new_compiler(*args, **kwargs)
  165. If MSVC10, initialize the compiler here and add /MANIFEST to linker flags.
  166. See Python issue 4431 (https://bugs.python.org/issue4431)
  167. if is_msvc(cc):
  168. from distutils.msvc9compiler import get_build_version
  169. if get_build_version() == 10:
  170. cc.initialize()
  171. for ldflags in [cc.ldflags_shared, cc.ldflags_shared_debug]:
  172. unique_extend(ldflags, ['/MANIFEST'])
  173. If MSVC14, do not silence. As msvc14 requires some custom
  174. steps before the process is spawned, we can't monkey-patch this.
  175. elif get_build_version() == 14:
  176. make_silent = False
  177. monkey-patch compiler to suppress stdout and stderr.
  178. if make_silent:
  179. cc.spawn = _CCompiler_spawn_silent
  180. return cc
  181. _msvc_classes = tuple(filter(None, (MSVCCompiler, MSVC9Compiler, MSVC14Compiler)))
  182. def is_msvc(cc=None):
  183. cc = _new_compiler() if cc is None else cc
  184. return isinstance(cc, _msvc_classes)
  185. if os.name == 'nt':
  186. if is_msvc():
  187. config_macros['inline'] = '__inline'
  188. Since we're shipping a self contained unit on Windows, we need to mark
  189. the package as such. On other systems, let it be universal.
  190. class BinaryDistribution(-title class_ inherited__">Distribution):
  191. def is_pure(self):
  192. return False
  193. distclass = BinaryDistribution
  194. else:
  195. Nothing to see here.
  196. distclass = Distribution
  197. Monkey-patch Cython to not overwrite embedded signatures.
  198. if cythonize:
  199. from Cython.Compiler.AutoDocTransforms import EmbedSignature
  200. old_embed_signature = EmbedSignature._embed_signature
  201. def new_embed_signature(self, sig, doc):
  202. Strip any `self` parameters from the front.
  203. sig = re.sub(r'\(self(,\s+)?', '(', sig)
  204. If they both start with the same signature; skip it.
  205. if sig and doc:
  206. new_name = sig.split('(')[0].strip()
  207. old_name = doc.split('(')[0].strip()
  208. if new_name == old_name:
  209. return doc
  210. if new_name.

网站声明:如果转载,请联系本站管理员。否则一切后果自行承担。

本文链接:https://www.xckfsq.com/news/show.html?id=2673
赞同 0
评论 0 条
巴山夜雨L1
粉丝 0 发表 16 + 关注 私信
上周热门
如何使用 StarRocks 管理和优化数据湖中的数据?  2944
【软件正版化】软件正版化工作要点  2863
统信UOS试玩黑神话:悟空  2823
信刻光盘安全隔离与信息交换系统  2718
镜舟科技与中启乘数科技达成战略合作,共筑数据服务新生态  1251
grub引导程序无法找到指定设备和分区  1217
华为全联接大会2024丨软通动力分论坛精彩议程抢先看!  164
点击报名 | 京东2025校招进校行程预告  163
2024海洋能源产业融合发展论坛暨博览会同期活动-海洋能源与数字化智能化论坛成功举办  161
华为纯血鸿蒙正式版9月底见!但Mate 70的内情还得接着挖...  157
本周热议
我的信创开放社区兼职赚钱历程 40
今天你签到了吗? 27
信创开放社区邀请他人注册的具体步骤如下 15
如何玩转信创开放社区—从小白进阶到专家 15
方德桌面操作系统 14
我有15积分有什么用? 13
用抖音玩法闯信创开放社区——用平台宣传企业产品服务 13
如何让你先人一步获得悬赏问题信息?(创作者必看) 12
2024中国信创产业发展大会暨中国信息科技创新与应用博览会 9
中央国家机关政府采购中心:应当将CPU、操作系统符合安全可靠测评要求纳入采购需求 8

加入交流群

请使用微信扫一扫!