DEV Community

Mohit Khare
Mohit Khare

Posted on

Publish your Command Line Python Package to the world in 5 minutes

Have you build something amazing and want everyone to use it ?

Yes, you can do that easily by sharing your package on PyPi.
Follow the guide to publish your first ever python package.

The Python Package Index (PyPI) is a repository of software for the Python programming language.PyPI helps you find and install software developed and shared by the Python community.It currently has over 173k projects.

If you are familiar with python, You must have came across -

pip install <package-name>
Enter fullscreen mode Exit fullscreen mode

Minimal structure for your project to be published requires following structure -

counter
        /__main__.py
README.md
LICENSE.txt
setup.py
Enter fullscreen mode Exit fullscreen mode

I am making a package named counter.(you can use yours)

In setup.py you need to specify all the components of your package.
Have a look at the file


setup(name='counter',
      version='1.0.0',
      description='A Python package for getting list of numbers from 1 to 100',
      url='https://github.com/<username>/<package-name>',
      entry_points={'console_scripts': ['counter= counter.__main__:main']},
      keywords=['counter', 'programming language ranking', 'index', 'programming language'],
      author='Mohit Khare (mkfeuhrer)',
      author_email='mohitfeuhrer@gmail.com',
      license='MIT',
      packages=['counter'],
      install_requires=[
          'requests'
      ],
      )

Enter fullscreen mode Exit fullscreen mode

Most of the field are represented via key names like name,version,etc.

  • Url field denotes the code repository url.
  • The field entry_points denotes the entry point of our package.

  • counter.main:main specifies to main function in main.py inside counter folder. (Do replace counter with your package name)

You can look for details here.

Next step is to make your LICENSE.txt. (I have used MIT license)

MIT License

Copyright (c) <year> <your name>

Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:

The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.

THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.
Enter fullscreen mode Exit fullscreen mode

Now fill up your README.md with some markdown text.

#counter

A Python package for getting list of numbers from 1 to 100.

### Dependencies

+ requests

## Contributors

- [Mohit Khare](https://github.com/mkfeuhrer)
Enter fullscreen mode Exit fullscreen mode

Now we are set to write our command line parser.

Let's start with main.py -

def main(argv=None):

    """
    :desc: Entry point method
    """
    if argv is None:
        argv = sys.argv

    try:
        parser = create_parser()


if __name__ == '__main__':
    sys.exit(main(sys.argv))
Enter fullscreen mode Exit fullscreen mode

We initialized our main.py to call main function which accepts arguments.
All we need is a create_parser() function now.

Develop your parser

We will use argparse package for parsing.

import argparse

def create_parser():
    parser = argparse.ArgumentParser()
    parser.add_argument('--counttill100',required=False,action='store_true',help='Print count till 100')

    return parser    

def main(argv=None):    

    """
    :desc: Entry point method
    """
    if argv is None:
        argv = sys.argv

    try:
        parser = create_parser()
                args = parser.parse_args(argv[1:])

        # Arguments initialization
        counttill100= args.counttill100

                # Parser check
        if counttill100:
            counttill100fun()

                except KeyboardInterrupt:
        print('\nGood Bye.')
            return 0

def counttill100fun():
    for i in range(1,101):
        print(i)


if __name__ == '__main__':
    sys.exit(main(sys.argv))

Enter fullscreen mode Exit fullscreen mode

We added a counttill100fun() function to print numbers from 1 to 100.
You can run

python __main__.py --counttill100
Enter fullscreen mode Exit fullscreen mode

Yay!! we successfully build our parser.

Publish your package

Register yourself on PyPi if you do not have a account.

Now generate distribution package by running this in your root folder.

pip install --user --upgrade setuptools wheel
python3 setup.py sdist
Enter fullscreen mode Exit fullscreen mode

Upload your package to PyPi , you will be prompted to enter your username and password.

twine upload dist/*
Enter fullscreen mode Exit fullscreen mode

Hurrah !! You just published your first package.

Hackerman

You can install it by infamous command

pip install <your-package-name>
Enter fullscreen mode Exit fullscreen mode

It's time to build some new projects and start contributing.

PS: Check my package here : Richest or do a simple

pip install richest
Enter fullscreen mode Exit fullscreen mode

Happy developing !!

Top comments (2)

Collapse
 
dbads profile image
Deepak Bharti

Awesome article 👍

Collapse
 
mkfeuhrer profile image
Mohit Khare

Thanks :)