Wiki
  • Introduction
  • πŸ‘ΎPenetration Testing
    • Application Security
      • Mobile App Security
        • Android Application Testing
          • Security Checklist
          • SSL Pinning Bypasses
          • Non-Proxy Aware Applications
            • Setting up VPN Server
            • Bypasses
          • Common Proxying Issues
          • Android Local Storage Checks
          • Android Task Hijacking
          • Kiosk Mode / Breakout Testing
          • Magisk on GenyMotion
        • iOS Application Testing
          • iOS Testing Using Objection
          • IPA Analysis Using MobSF
          • iOS Jailbreak Bypass
          • Decrypting iOS Apps
          • iOS Reverse Engineering
          • Jailbreak Detection Bypasses
          • iOS Local Storage Checks
          • Installing IPA
          • ATS Auditing
          • iOS Jailbreaking
          • Frida Pinning Bypasses
          • iOS Jailbreaking
        • Code Security
        • Frida on Windows
      • Web Application Security
        • Web Shells
        • CSV Injection
        • Measure Response Time using CURL
        • OSINT
          • EyeWitness
        • GraphQL Hacking
      • API Security
        • Security Checklist
        • Postman and Burp
        • CURL via BurpSuite
        • SOAP API Pentesting
    • Infrastructure Security
      • Network Infrastructure
        • Red Team Powershell Scripts
        • Mounting NFS Shares
        • Password Cracking/Auditing
        • Remote Access Sheet
        • Password Cracking Using Hashcat
        • Calculate IP Addresses from CIDR
        • Grep IP addresses or IP Ranges from a File
        • Default Credentials Checking
        • Check SSL/TLS Certificates
        • Log a terminal session
        • Unauthenticated Mongo DB
        • Microsoft SQL Server (MSSQL)
        • NTP Mode 6 Vulnerabilities
        • BloodHound
        • AD Offensive Testing
        • CrackMapExec
        • Select all IP addresses in Sublime Text
        • Convert CIDRs to an IP address list
        • Microsoft Exchange Client Access Server Information Disclosure
        • Web Server HTTP Header Internal IP Disclosure
        • smbclient.py
        • GetUserSPNs.py
        • Get-GPPPassword.py
        • SMBMap
        • Mounting Shares
        • mitm6
        • AD Attacks
        • Weak IKE Security Configurations
        • Locked BIOS Password Bypass
      • Wireless Security
        • Cached Wireless Keys
        • Aircrack Suite
    • SSL/TLS Security
    • Secure Code Review
      • Python
      • Semgrep
        • Semgrep to HTML Report
    • Cloud Security
      • Cloud Penetration Testing
    • Social Engineering
      • Simulated Phishing
        • GoPhish
    • Tool Usage
      • Docker
      • Split
      • PhantomJS
      • Aquatone
      • Tmux
      • Ipainstaller
      • Public IP From Command Line
      • Wifite
      • IKE Scan
      • Grep
      • Pulling APKs
      • Bitsadmin
      • Drozer
      • Iptables
      • Python Web Server
      • Crackmapexec
      • Impacket
      • Nessus
      • Adding SUDO User
      • Nmap
      • Metasploit Payloads
      • SMTP Open Relay
      • SQLMap
      • Screen
      • Remove All After Colon
      • Remove Old Linux Kernels
      • CURL
      • Hashcat
      • Secure Copy Protocol (SCP)
      • SSH & PGP Tools
      • IP Calculator
      • BloodHound
      • Netcat File Transfer
      • OpenVAS
      • BurpSuite
      • Exiftool
      • Python Virtual Environments
    • Errors and Solutions
      • Kill Process On Specific Port
      • Kill SSH Port Forwarding
      • SSH Key
      • Expanding Disk on Kali VM
    • Scoping
      • Scoping Questionnaires
        • Mobile App Testing
    • OSINT
      • Dark Web OSINT
      • Certificate Chain Check
      • EyeWitness - Web Service Screenshot
      • Tor to Browse Onion Links
      • DarkDump - Scan Dark Web for Onion Links
      • Domain related File Search
      • Google Dorking
      • IP / Network Blocks owned by a Company
  • ⌨️Programming
    • Automation
      • Running a Service at Boot
      • Network Connectivity Cron
    • Python
      • Adding Columns in Pandas
      • Copy Entire Column Data To New Column Pandas
      • Loading Progress Bar
      • Reorder Columns in Pandas
      • Filename with Date/Time Stamp
      • Command Line Arguments
      • Changing Date Format
      • Removing Index Column Pandas
      • Regex - Remove HTML Tags
      • Column Header Mapping
  • 🌐Miscellaneous
    • Scripts
      • Clickjacking Checker
      • Bulk WHOIS
      • SMB Signing Check
      • FDQN to IP Address
      • Grep IP Addresses
      • Nessus Parser
      • Build Review Audit
      • Nessus Merger
      • Nmap2CSV
      • Remove Audio From Videos
    • Favourite Reads/Links
    • Hacking Posters
    • Windows Developer VMs
    • Windows Workspaces
    • GitHub Pages
    • Interview Prep
      • Senior Penetration Tester
    • CVSS Formula
    • Android Rooting
      • Lineage OS 18.1 on OnePlus X
      • TWRP Recover on OnePlus X
      • Magisk Rooting
    • Presentation Slides
      • BlackHat - USA [2022]
  • 🐞Vulnerability Wiki
    • 🌐APPLICATION LEVEL
      • πŸ”’AUTHENTICATION
        • Authentication Bypass
        • Lack of Password Confirmation
        • 2FA Code Brute-forceable
        • Lack of Verification
        • Lack of Throttling on Form Submissions
        • Lack of Rate Limiting on Login
        • Weak Password Complexity Rules
        • πŸ–₯️SESSION MANAGEMENT
        • πŸ”‘ACCESS CONTROL
      • πŸ”’INPUT VALIDATION
      • βž—CRYPTOGRAPHY
      • πŸ“‰LOGGING
      • πŸ“•DATA PROTECTION
      • πŸ“²COMMUNICATION
      • πŸ‘¨β€πŸ’»MALICIOUS CODE
      • πŸ’‘LOGIC
      • πŸ—„οΈFILE UPLOAD
      • βš™οΈAPI ISSUES
      • πŸ”CONFIGURATIONS
    • πŸ’ΎINFRASTRUCTURE LEVEL
      • ICMP Timestamp Request Remote Date Disclosure (CVE-1999-0524)
      • ASP.NET Debug Mode Validation
Powered by GitBook
On this page
  • Example 1: Generate Help Argument and Message
  • Example 2: Handle a String Argument
  • Example 3: Handle an Integer Argument
  • Example 4: Handle True and False Toggles
  • Example 5: Treat Argument Values as List
  • Example 6: File as command line argument for argparse - error message if argument is not valid
  • Example 7: File Extension Checking - argsparse
  • Example 8: Require either of two arguments using argparse
  • Example 8: If arg is A, do this, if B do that, if none of the above show help and quit

Was this helpful?

  1. Programming
  2. Python

Command Line Arguments

Example 1: Generate Help Argument and Message

Consider the code sample below:

import argparse

parser = argparse.ArgumentParser(description='A test program.')
args = parser.parse_args()
$ ./test.py -h
$ ./test.py --help

A test program.

optional arguments:
  -h, --help  show this help message and exit

Example 2: Handle a String Argument

import argparse

parser = argparse.ArgumentParser(description='A test program.')

parser.add_argument("print_string", help="Prints the supplied argument.")

args = parser.parse_args()

print(args.print_string)
usage: test.py [-h] [print_string]

A test program.


positional arguments:

  print_string  Prints the supplied argument.


optional arguments:

  -h, --help    show this help message and exit

To define and parse optional arguments, you can use β€œβ€“β€ (double dash) and change their default values using the β€œdefault” argument.

import argparse

parser = argparse.ArgumentParser(description='A test program.')

parser.add_argument("--print_string", help="Prints the supplied argument.", default=”A random string.”)

args = parser.parse_args()

print(args.print_string)
$ ./test.py --print_string My-Test-String
My-Tesr

You can also define shorthand versions of the argument using β€œ-” (single dash) to reduce verbosity.

import argparse

parser = argparse.ArgumentParser(description='A test program.')

parser.add_argument(β€œ-p”, "--print_string", help="Prints the supplied argument.", default=”A random string.”)

args = parser.parse_args()

print(args.print_string)
$ ./test.py -p Test-String

Example 3: Handle an Integer Argument

import argparse

parser = argparse.ArgumentParser(description='A test program.')

parser.add_argument("-p", "--print_string", help="Prints the supplied argument.", type=int)

args = parser.parse_args()

print(args.print_string)
usage: test.py [-h] [-p PRINT_STRING]

test.py: error: argument -p/--print_string: invalid int value: 'LinuxHint.com'

Example 4: Handle True and False Toggles

import argparse

parser = argparse.ArgumentParser(description='A test program.')

parser.add_argument("-p", "--print_string", help="Prints the supplied argument.", action="store_true")

args = parser.parse_args()

print(args.print_string)

Example 5: Treat Argument Values as List

If you want to get multiple values at once and store them in list, you need to supply β€œnargs” keyword in following format:

import argparse

parser = argparse.ArgumentParser(description='A test program.')

parser.add_argument("-p", "--print_string", help="Prints the supplied argument.", nargs='*')

args = parser.parse_args()

print(args.print_string)
$ ./test.py -p β€œa” β€œb”
['a', 'b']

Example 6: File as command line argument for argparse - error message if argument is not valid

You just need to write a function which checks if the file is valid and writes an error otherwise. Use that function with the type option. Note that you could get more fancy and create a custom action by subclassing argparse.Action, but I don't think that is necessary here. In my example, I return an open file handle (see below):

#!/usr/bin/env python

from argparse import ArgumentParser
import os.path


def is_valid_file(parser, arg):
    if not os.path.exists(arg):
        parser.error("The file %s does not exist!" % arg)
    else:
        return open(arg, 'r')  # return an open file handle


parser = ArgumentParser(description="ikjMatrix multiplication")
parser.add_argument("-i", dest="filename", required=True,
                    help="input file with two matrices", metavar="FILE",
                    type=lambda x: is_valid_file(parser, x))
args = parser.parse_args()

A, B = read(args.filename)
C = ikjMatrixProduct(A, B)
printMatrix(C)

Example 7: File Extension Checking - argsparse

import argparse
import os.path

parser = argparse.ArgumentParser()

def file_choices(choices,fname):
    ext = os.path.splitext(fname)[1][1:]
    if ext not in choices:
       parser.error("file doesn't end with one of {}".format(choices))
    return fname

parser.add_argument('fn',type=lambda s:file_choices(("csv","tab"),s))

parser.parse_args()

Example 8: Require either of two arguments using argparse

import argparse

parser = argparse.ArgumentParser()
group = parser.add_mutually_exclusive_group(required=True)
group.add_argument('--foo',action=.....)
group.add_argument('--bar',action=.....)
args = parser.parse_args() 

If you need some check that is not provided by the module you can always do it manually:

pa = argparse.ArgumentParser()
...
args = pa.parse_args()

if args.foo is None and args.bar is None:
   pa.error("at least one of --foo and --bar required")

Example 8: If arg is A, do this, if B do that, if none of the above show help and quit

import argparse

parser = argparse.ArgumentParser()
parser.add_argument("a")
args = parser.parse_args()

if args.a == 'magic.name':
    print 'You nailed it!'

adding to it:

...
parser.add_argument("a", nargs='?', default="check_string_for_empty")
...
if args.a == 'check_string_for_empty':
    print 'I can tell that no argument was given and I can deal with that here.'
elif args.a == 'magic.name':
    print 'You nailed it!'
else:
    print args.a

Or try the following:

Here's the way I do it with argparse (with multiple args):

parser = argparse.ArgumentParser(description='Description of your program')
parser.add_argument('-f','--foo', help='Description for foo argument', required=True)
parser.add_argument('-b','--bar', help='Description for bar argument', required=True)
args = vars(parser.parse_args())

args will be a dictionary containing the arguments:

if args['foo'] == 'Hello':
    # code here

if args['bar'] == 'World':
    # code her

PreviousFilename with Date/Time StampNextChanging Date Format

Last updated 3 years ago

Was this helpful?

⌨️