代码之家  ›  专栏  ›  技术社区  ›  Shan-Desai askovpen

将Python3脚本设置为CLI

  •  0
  • Shan-Desai askovpen  · 技术社区  · 7 年前

    我有一个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 或任何其他辅助模块,并坚持核心 皮普 ?

    2 回复  |  直到 6 年前
        1
  •  0
  •   mehdix    7 年前

    在这一点上,我不确定应该在bin/偏转文件中写入什么?

    没有什么。您不应该在 bin

    我建议你使用 flit 和 pyproject.toml . 这将大大简化您的项目。首先添加一个 文件(而不是setup.py):

    [build-system]
    requires = ['flit']
    build-backend = 'flit.buildapi'
    
    [tool.flit.metadata]
    module = 'deflection'
    requires-python = '>=3'
    description-file = 'README.rst'
    requires = ['influxdb-python']
    
    [tool.flit.scripts]
    deflection = 'deflection.deflection:main'
    

    然后使用 flit publish .

        2
  •  0
  •   Shan-Desai askovpen    7 年前

    正如@schlamar在评论部分提到的:

    我将所有代码添加到 __name__=='__main__' main() 并更名为 main(args) 作用于 send_data(args) .

    def send_data(args):
      """ refactor the function name"""
    
    def 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:
                send_data(...) # 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:
                send_data(..) # custom args to main function
    
            except KeyboardInterrupt as e:
                # safe exit if CTRL C pressed
                sys.exit(0)
    

    bin/deflection 我补充说

    #!/usr/bin/env python3
    
    import deflection
    
    if __name__ == '__main__':
       deflection.main()
    

    virtualenv pip install . 在回购协议和 $ deflection 检查它是否运行