1

I want to create my own command line utility tools, that we can run at the command line by simply typing the command name. git is a great example of the sort of commands I want to create.

I want to achieve this using python.

I have followed:

  1. https://dev.to/pybash/how-to-create-a-command-line-utility-using-python-4ae6

I have tried this before from other sources, but cannot implement it.

For this one when I do:

C:\Users\username> search.py .py D:\Programming

I get nothing, nothing happens. Only the file search.py opens in VS code.
Note: I have tried adding #!/usr/bin/env python and #!/usr/bin/python to start of the file, it does not help.

#Expected output
D:\Programming\CLI-Utilities\search.py
D:\Programming\CLI-Utilities\calc.py
D:\Programming\etc.py
No. of files matched = 3

Code in search.py:

# search.py - CLI-Utilities - play4Tutorials.hashnode.dev, github.com/play4Tutorials
try:
    import os  # stdlib
    import sys  # stdlib
# Exception and Error Handling
except ImportError as e:
    print("Error: Some modules could not be imported from stdlib('sys' and 'os')")

keyword = sys.argv[1]  # Get the keyword that is to be searched for
path = " ".join(sys.argv[2:])  # Get the path where to search for the keyword

filesMatched = 0  # Initialize filesMatched as 0

# Function to search the keyword in a given directory
def search_files(keyword, path):
    filesFound = filesMatched
    for root, dirs, files in os.walk(
        path
    ):  # Use os.walk(path) to loop through the given directory and get the root, dirs, and files
        for file in files:  # Loop through all the files in the given directory.
            if keyword in file:  # Check if keyword is in filename
                filesFound += 1  # Counter to see how many files matched
                print(
                    " " + root + "\\" + str(file) + "\n"
                )  # Print out the full file path for every matching file
                if (
                    filesFound == 0
                ):  # Check if no files matched the given keyword and print the same
                    print(
                        "No matching files in the given directory! Try another directory!"
                    )
    # If 1 or more files are matched then print the same
    print(f"No. of files matched: {filesFound}")


try:
    search_files(keyword, path)  # Call the function
# Error and Exception Handling
except FileNotFoundError as e:
    print(
        "Error: FileNotFoundError occured! Make sure you entered the correct path and entered it correctly."
    )
except Exception as e:
    print(f"Error: Some Error occured! \nDetails: {e}")

Screenshot of my path variables, after following the "how to run it from anywhere" instructions path variables

Curious Learner
  • 1,182
  • 1
  • 4
  • 17
  • I have tried it with just one `print("Hello world")` in the file. It still does not work. – Curious Learner Jan 03 '22 at 07:50
  • You want to run the Python script? Write `$python C:\\path\to\your\file.py arguments`. – FLAK-ZOSO Jan 03 '22 at 07:53
  • @FLAK-ZOSO I want it to work like `git`, `pip`, `node`, etc commands. Please see the link provided. – Curious Learner Jan 03 '22 at 07:55
  • Yes, I understood, I'm creating a similar thing with python (https://github.com/FLAK-ZOSO/Prompt) but I still haven't implemented a search command. Then, you copy-pasted the code from the site? – FLAK-ZOSO Jan 03 '22 at 07:58
  • 1
    It's hard to imagine a situation where you could fail to `import os` and `import sys` and still do something useful from within your script. – tripleee Jan 03 '22 at 08:08
  • You need to read the bottom part of your linked site *"How to run it from anywhere"*. – Mark Setchell Jan 03 '22 at 08:11
  • The tutorial you link to seems to be a bit dubious. The trick you are looking for is to save your script (or a launcher for it, if you are on Windows) in your `PATH`. The proper solution is to package your script into an installable module and set its `console_scripts` in `setup.py` (or whatever [the equivalent is in `pyproject.toml`](/q/63326840)) to point to your script. At this point, the console script should arguably not have a `.py` extension. Then, `pip install` will take care of the practical arrangements to make the command executable when you install the module. – tripleee Jan 03 '22 at 08:12
  • @tripleee I have followed the linked site "How to run it from anywhere", and did just as it said. But it does not work. – Curious Learner Jan 03 '22 at 08:15
  • (You seem to be replying to @MarkSetchell's comment actually.) – tripleee Jan 03 '22 at 08:16
  • Then [edit] to show us your `PATH` in the environment where it doesn't work. – tripleee Jan 03 '22 at 08:16
  • @tripleee I am replying to you. How can I package my script? Can you please help me by providing some learning sources. – Curious Learner Jan 03 '22 at 08:19
  • The immediate fix is to review the "how to run it from anywhere" instructions and figure out which part of it you failed to do. – tripleee Jan 03 '22 at 08:19
  • @tripleee please see the image, i have added just now – Curious Learner Jan 03 '22 at 08:24
  • Apparent duplicate of https://stackoverflow.com/questions/65346956/why-does-running-a-sh-script-from-visual-studio-open-the-file-instead-of-runnin – tripleee Jan 03 '22 at 08:27
  • Yes, it is a similar problem. So, what to associate with what? --in my case. – Curious Learner Jan 03 '22 at 08:30
  • If you cannot yet move off Windows, try https://superuser.com/questions/669142/how-to-set-file-association-in-windows-explorer – tripleee Jan 03 '22 at 08:42
  • Did you start a new Command Prompt after changing your PATH? – Mark Setchell Jan 03 '22 at 08:48
  • @MarkSetchell yes, new prompt – Curious Learner Jan 03 '22 at 08:52
  • Your PATH shows `D:\PythonDevelopment` but your directory seems to be `D:\Programming`? – Mark Setchell Jan 03 '22 at 08:57
  • No, that is the expected output that I copied from the source-link that I was following – Curious Learner Jan 03 '22 at 09:03
  • @MarkSetchell At least provide some source on how to create cli tools like pip, git, node, etc... – Curious Learner Jan 03 '22 at 09:13

0 Answers0