0

I have python script that need to read some data using requests.get(url, headers=headers)

the program is executed from terminal as follow:

python prog.py --path http://url.com -hget "key :value"

the string argument from -hget (headers for get) is parsed to dict and it's worked, here is the function

def parse_headers(headers) -> dict:
    """
    Return parsed headers to dict
    """

    if type(headers) == dict:
        return headers

    elif type(headers) == list:
        items = ''
        for header in headers:
            # Convert each headers to "'key' : 'value'"
            header_split = header.split(':')
            key = header_split[0].replace(' ', '')
            value = header_split[1].replace(' ', '')
            header = '"{key}" : "{value}"'.format(key=key, value=value)
            items += header + ', '

        return json.loads('{' + items[:-2] + '}')

Oh no.. I just realize while typing this, the parse_header(args.hget) will also convert every value to string, will work on this later.

For example, if the user execute this command from terminal:

python prog.py --path http://url.com -hget "key : $abc.edf" "id: 1"
import argparse
import json
import requests

parser = argparse.ArgumentParser()
parser.add_argument('--path', required=True, help="path or url")
parser.add_argument('-HG', '--hget', nargs='*', help="extra source of information for GET request")
args = parser.parse_args()

# parsing header argument
headers = parse_headers(args.hget)
path = args.path

print(headers)
# the header should produce like this:
# {'key' : '$abc.edf', 'id' : '1'}
# however what i got is:
# {'key' : '.edf', 'id' : '1'}

# request GET
request = requests.get(path, headers=parse_headers(headers))

the string which contain $ is somehow gone. how do i keep the string as it is?

ZEDT
  • 9
  • 1
    This is a shell problem, not a Python problem; you can't fix it by changing your Python because the original data is destroyed before the Python interpreter is even started. Use single quotes instead of double quotes: `-hget 'key : $abc.edf' 'id: 1'` -- otherwise the shell variable `$abc` is put in place of that substring. – Charles Duffy Mar 05 '22 at 04:33

0 Answers0