Just starting to learn python and playing around with passing command line options to a python script. I'm trying to concatenate two or more arguments and pass it on to a string variable,
e.g.,
myscript.py http://www.domain.com 1234
put it in to a string variable called url
, which then should have the value of "http://www.domain.com:1234"
I'm not quite sure on how to archive that. It's quite straigh开发者_开发知识库t forward to do it with raw_input
and some string manipulation, but I wonder if this can be done with argparse
as well.
import argparse
parser = argparse.ArgumentParser()
parser.add_argument('server') # first positional argument
parser.add_argument('port') # second positional argument
args = parser.parse_args()
url = '%s:%s' % (args.server, args.port)
print url
argparse is one way to solve it, but may be overkill if you're just learning (YMMV).
If you import the sys
module, the command line arguments passed to you are available in a list of strings at sys.argv
import sys
if len(sys.argv) < 3:
print "Not enough args!"
sys.exit(0)
# sys.argv[0] is the name of your script, the rest are parameters
url = "%s:%s" % (sys.argv[1], sys.argv[2])
print url
Why not do,
argstring = ':'.join(args[1:])
If you want a variable with the string http://www.domain.com:1234 from command line input then do the following:
if len(sys.argv) >= 3:
result = '%s:%s' % tuple(sys.argv[1:3])
Thanks Amber,
that was exactly what I was looking for
#!/usr/bin/python
from urllib import urlopen
import argparse
usage='will be using it later'
parser=argparse.ArgumentParser(formatter_class=argparse.RawDescriptionHelpFormatter, description=usage, add_help=False)
parser.add_argument('link')
parser.add_argument('port')
args = parser.parse_args()
url = '%s:%s' % (args.link, args.port)
link = urlopen(url)
content=link.read()
print(content)
just a bit confused with this line "url = '%s:%s' % (args.link, args.port)" does that line take the arguments in brackets and add it to the string variable 'url'?
Jack
just a bit confused with this line "url = '%s:%s' % (args.link, args.port)" does that line take the arguments in brackets and add it to the string variable 'url'?
That format is actually not recommended any more. ( see http://docs.python.org/tutorial/inputoutput.html). The simplest way to do the same with a currently recommended method would be:-
url = '{0}:{1}'.format( args.link , args.port )
where {n} is the nth variable within format( variables ). This method will always convert the arguments to a string for you.
The older method using %s does the same; the 's' meaning turn an argument into a string, but there has to be exactly as many '%s' flags within the string as there are arguments after the % sign after the string. Don't worry about this, but if you're learning, use .format().
精彩评论