简体   繁体   中英

How to pass command line arguments to a url string

I have a report I'm downloading from a url using requests in python like this:

dls = 'http://somepage/reporting?tags=name&daysback=days'
resp = requests.get(dls)

What I want is for 'tag' and 'daysback' in the url above to be arguments passed in the command line using sys argv.

For example, I want something like this:

try:
     tag = sys.argv[1]
     daysback = sys.argv[2]
except IndexError:
     raise IndexError('Example/ python script.py [tag] [daysback]')

So if my tag name was 'produce' and 'daysback' was 10, for example:

I'd expect the url to look like this:

dls = 'http://somepage/reporting?tags=produce&daysback=10'

and command line argument to be:

python script.py [produce] [10]

Does anyone know how I can do this?

import sys

tag = sys.argv[1]
daysback = sys.argv[2]

url = 'http://somepage/reporting?tags=' + tag + '&daysback=' + daysback

resp = requests.get(url)

Alternatively:

url = 'http://somepage/reporting?tags={}&daysback={}'.format(tag, daysback)

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