Create a command-line calculator app, mycal, using Python and argparse. Run it from the Terminal like:
mycal-s"+"-f"100"-n"200"
Follow these steps to build it:
Step 1: Create the Python Script
Create a file named mycal and add the following script:
#!/usr/bin/env python3import argparsedefcalculate(sign,first,second):try: first =float(first) second =float(second)if sign =="+":return first + secondelif sign =="-":return first - secondelif sign =="*":return first * secondelif sign =="/":return first / secondelse:return"Invalid operator!"exceptExceptionas e:returnf"Error: {e}"defmain(): parser = argparse.ArgumentParser(description="Simple CLI Calculator") parser.add_argument('-s','--sign',required=True,help='Operator: +, -, *, /') parser.add_argument('-f','--first',required=True,help='First number') parser.add_argument('-n','--second',required=True,help='Second number') args = parser.parse_args() result =calculate(args.sign, args.first, args.second)print(f"Result: {result}")if__name__=="__main__":main()
Step 2: Make It Executable
In the Terminal, run:
Move it to your path:
Now, use it like:
Output:
Notes
-s for sign/operator
-f for the first number
-n for the second number
Use full names: --sign, --first, --second if preferred
Interested in expanding functionality with power (**), modulus (%), or string expressions? Let me know!
Issue with Missing Directory and Operation Permission
The user is experiencing two issues on their macOS system:
Missing Directory: The /usr/local/bin directory does not exist, only /usr/local is present. This might require creating the directory if needed by running:
Ensure you have the proper permissions or use sudo if necessary.
Permission Error: When trying to move a file to /bin using:
The operation fails with "Operation not permitted". This could be due to system integrity protection (SIP) preventing modifications to system directories.
Suggestions
Create Missing Directory: If you need /usr/local/bin, create it with:
Address Operation Not Permitted: Try using a different directory such as /usr/local/bin:
Ensure SIP is not overly restrictive for necessary operations or consider alternative directories like /usr/local/bin for installing custom binaries.
If you're using macOS and need to move CLI tools to a secure location, follow these steps. System Integrity Protection (SIP) in macOS restricts access to certain system folders like /bin.
💡 Recommended Approach: Create a Custom Bin Directory
🔧 Step-by-Step Guide
1. Create a Custom CLI Tools Folder
2. Transfer Your Script
If mycal is in the current directory:
3. Update Your PATH Variable
Edit your shell configuration file:
zsh: ~/.zshrc
bash: ~/.bash_profile or ~/.bashrc
Add this line:
Reload your shell configuration:
✅ Verify It
Run your script:
Expected output:
You can edit mycal anytime in $HOME/.mybin. For features like history or logging, feel free to reach out!