简体   繁体   中英

how to add arguments in python3.7

How can i add system arguments in python3.7? Im trying to make an IP finder and i want the syntax to be like this:

python3 ipfind.py -u www.google.com

and it prints the google ip.

Thanks!

You can use argparse or OptionParser. Please see the documentation for the OptionParser at the following URL:

OptionParser

Here is the simple code to get the IP of a given URL.

''' Simple program to return the IP.
You need to add lot more exception handling. 
''' 
import socket
from optparse import OptionParser

parser = OptionParser()
parser.add_option("-u", "--url", dest="url",
              help="specify url to find the IP", action="store")

(options, args) = parser.parse_args()

try:
    if options.url:
        ip = socket.gethostbyname(options.url)
        print("URL: %s IP: %s" %(options.url, ip))
except:
    print("Unable to get IP address for URL %s" %(options.url))
    raise

A sample run:

$python test3.py -u google.com
URL: google.com IP: 172.217.8.14

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM