我有一个python3脚本,它的结构如下。我希望通过以下方式将此代码作为CLI实用程序(而不是python3模块)提供
pip
. 它之所以不是python3模块,是因为它的逻辑非常直截了当,我认为将代码重构成更小的python文件使其成为模块没有任何好处。
deflection.py
def func1():
"""some useful function here"""
def main(args):
""" My MAIN Logic here!!"""
def parse_args():
"""Parse Arguments if Passed else use configuration file"""
parser = argparse.ArgumentParser(description='what the CLI should do.')
parser.add_argument('--ip', type=str, required=False, help='descp@1')
# Add more arguments (trimmed for code brevity)
return parser.parse_args()
if __name__ == '__main__':
args = parse_args()
CONF = dict() # create a dict for reading a `conf.json` file from `/etc/` folder
with open(CONF_PATH) as cFile:
_conf = json.load(cFile)
CONF = _conf['Key_Of_Interest']
# Check Argument conditions
if condition_1:
print('Starting Script in Default Mode. Reading Conf File conf.json')
try:
main(...) # pass all the default args here
except KeyboardInterrupt as e:
# if CTRL C pressed safe exit
sys.exit(0)
elif condition_2:
# if one particular argument wasn't mentioned, stop script
sys.exit(1)
else:
print('Starting Script with Custom Arguments.')
try:
main(..) # custom args to main function
except KeyboardInterrupt as e:
# safe exit if CTRL C pressed
sys.exit(0)
我正在跟踪
Python-Packaging Tutorial
CLI
对于python模块。
.
|-- bin
| `-- deflection
|-- deflection
| |-- deflection.py
| `-- __init__.py
|-- MANIFEST.in
|-- README.rst
`-- setup.py
setup.py
from setuptools import setup
def readme():
with open('README.rst') as f:
return f.read()
setup(name='deflection',
version='0.1',
description='Extract Micro-Epsilon OptoNCDT values and store into InfluxDB',
long_description=readme(),
url='https://mypersonalgitlabLink.com/awesomeCLIProject',
author='Monty Python',
author_email='Monty@python.org',
license='GPLv3',
packages=['deflection'],
scripts=['bin/deflection']
install_requires=[
'influxdb-python'
],
zip_safe=False)
bin/deflection
文件
#!/usr/bin/env python3
from .deflection import main # NOT SURE Here! because main() requires arguments
我可以简单地决定
chmod +x deflection.py
influxdb-python
我希望通过
i、 当一个人这样做的时候
`pip3 install deflection`
用户可以直接做
$ deflection --arg1='test'
我如何在没有使用的情况下实现这一点
click
或任何其他辅助模块,并坚持核心
皮普
?