我正在尝试遵循 python packaging docs 中写入的建议和结构。在设置函数中,您可以使用 tests_require
指定测试的依赖项。您只需指定 scripts
即可在安装时运行脚本。但是我可以有一个仅在测试设置的情况下运行的脚本吗?
from setuptools import setup
# To use a consistent encoding
from codecs import open
from os import path
import subprocess
from setuptools import setup
from setuptools.command.test import test
class setupTestRequirements(test, object):
def run_script(self):
cmd = ['bash', 'bin/test_dnf_requirements.sh']
p = subprocess.Popen(cmd, stdout=subprocess.PIPE)
ret = p.communicate()
print(ret[0])
def run(self):
self.run_script()
super(setupTestRequirements, self).run()
...
setup(
...
scripts=['bin/functional_dnf_requirements.sh'],
install_requires=['jira', 'PyYAML'],
tests_require=['flake8', 'autopep8', 'mock'],
cmdclass={'test': setupTestRequirements}
)
最佳答案
这并不意味着scripts
中的文件将在软件包安装时执行。关键字 scripts
用于标记包中的 python 文件,这些文件旨在在包安装后作为独立程序运行(也许这个名称有 pip 误导)。示例:您有一个文件垃圾邮件
,其内容为:
#!/usr/bin/env python
if __name__ == '__main__':
print('eggs!')
如果您通过将此文件添加到 setup.py
中的 scripts
来将此文件标记为脚本:
from setuptools import setup
setup(
...
scripts=['spam'],
)
安装包后,您可以在终端中将 spam
作为独立程序运行:
$ spam
eggs!
阅读this tutorial有关命令行脚本的更多信息。
<小时/>现在,如果您想在测试时执行自定义代码,则必须覆盖默认的 test
命令。在您的 setup.py
中:
from setuptools.command.test import test
class MyCustomTest(test):
def run(self):
print('>>>> this is my custom test command <<<<')
super().run()
setup(
...
cmdclass={'test': MyCustomTest}
)
现在,运行测试时您会注意到额外的打印:
$ python setup.py test
running test
>>>> this is my custom test command <<<<
running egg_info
...
running build_ext
----------------------------------------------------------------------
Ran 0 tests in 0.000s
OK
<小时/>
编辑:如果您想在执行测试之前运行自定义 bash 脚本,请调整 MyCustomTest.run()
方法。示例脚本 script.sh
:
#!/usr/bin/env bash
echo -n ">>> this is my custom bash script <<<"
调整setup.py
中的MyCustomTest
类:
import subprocess
from setuptools import setup
from setuptools.command.test import test
class MyCustomTest(test):
def run_some_script(self):
cmd = ['bash', 'script.sh']
# python3.5 and above
# ret = subprocess.run(cmd, stdout=subprocess.PIPE, universal_newlines=True)
# print(ret.stdout)
# old python2 versions
p = subprocess.Popen(cmd, stdout=subprocess.PIPE)
ret = p.communicate()
print(ret[0])
def run(self):
self.run_some_script()
super().run()
输出:
$ python setup.py test
running test
>>> this is my custom bash script <<<
running egg_info
writing spam.egg-info/PKG-INFO
writing dependency_links to spam.egg-info/dependency_links.txt
writing top-level names to spam.egg-info/top_level.txt
reading manifest file 'spam.egg-info/SOURCES.txt'
writing manifest file 'spam.egg-info/SOURCES.txt'
running build_ext
----------------------------------------------------------------------
Ran 0 tests in 0.000s
OK
关于python - PyPa setup.py 测试脚本,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47443660/