- 1 year ago
How to use argparse without passing 'python' in CMD?
To use argparse
without explicitly passing 'python' in the command prompt (CMD), you can create a Python script and make it executable by setting the appropriate shebang line. This allows you to run the script directly without explicitly invoking the Python interpreter.
Here's how you can do it:
Create the Python Script:
Create a new Python script (e.g.,myscript.py
) with yourargparse
code.python#!/usr/bin/env python
import argparse
def main():
parser = argparse.ArgumentParser(description='Example argparse usage')
parser.add_argument('--input', type=str, help='Input file')
parser.add_argument('--output', type=str, help='Output file')
args = parser.parse_args()
print('Input:', args.input)
print('Output:', args.output)
if __name__ == '__main__':
main()
Make the Script Executable:
In order to run the script without explicitly passing 'python' in CMD, you need to make the script executable on your system. To do this:On Unix-like systems (Linux, macOS):
Set the shebang line to point to the location of the Python interpreter. The script will be run as an executable.bashchmod +x myscript.py
On Windows:
Windows does not natively support the shebang mechanism. However, you can create a batch file to run the script.Create a batch file (e.g.,
myscript.bat
) with the following content:batch@python myscript.py %*
Now, you can run the script using
myscript.bat
without explicitly typing 'python'.
Run the Script:
After making the script executable (Unix-like systems) or creating the batch file (Windows), you can run the script as follows:On Unix-like systems:
bash./myscript.py --input input.txt --output output.txt
On Windows:
batchmyscript.bat --input input.txt --output output.txt
By making the script executable (Unix-like systems) or creating a batch file (Windows), you can run your argparse
script without needing to explicitly pass 'python' in CMD.