This is the first post in a series on creating Python CLI-tools in Windows. However, this post will be applicable independently of the programming language. To start off the series I want to show you how to set up a directory where we can store the tools and make them accessible in the terminal, independent of our current working directory.
First, I create a folder named tools in my user directory. Inside it, I create a folder named bin. The name bin comes from the Linux convention of storing executables (binaries) and scripts in directories named bin, e.g.
~/bin. Where the last one is where the user stores their own programs, similar to what we are currently working on. So let us continue.
Secondly, we need to add the newly created bin directory,
C:\Users\<username>\tools\bin, to our path. To add it to the path:
- Open advanced system settings, you can search for it in the windows search bar
- Press the button Environment variables. This opens a new window, with two lists. The upper one is for personal environment variables and the lower one for system-wide once.
- Mark the path variable in your personal list and then press the edit button.
- Now you can add a new row, paste the path to the bin directory and save.
Now we can add an executable file to the bin directory and it will be accessible in the terminal. So now the core functionality for this post is done. If you are using a compiled language, you just need to add the compiled binary to the directory and you will be able to run it. However, I generally prefer to use Python, especially for these types of tasks. Therefore, I will go through some problems I encountered when trying to run python scripts using this method in the next post.
A final note, I want to recommend tip 28 from the book The Pragmatic Programmer, 20th Anniversary Edition: “Always Use Version Control”. This is the reason we created the tools directory,
C:\Users\<username>\tools. I recommend turning the tools directory into a git-repository and uploading it to a remote repository like GitHub. As this isn't the focus of the post, I won't cover how this is done here. There already exist plenty of posts on how to get started with git, however, if you want me to cover the subject leave a comment. In this case, the main purpose of the repository is to have a way to easily re-install all your tools. I would, however, recommend having the repository private so you think less about writing pretty code and more about just solving the problem. Personally, I would easily be sidetracked if I had it as a public repository.