1

So I've been curious to figure out how to do argument-parsing inside of input functions. For example:

a = input('enter something here: ')

now, lets say, if I input '--url example.com --data some_data_here' for example in a, how would I read the content after '--url' and '--data' separately? Help would be greatly appreciated :)

Jack
  • 39
  • 5
  • Make a custom function. – PCM Nov 04 '21 at 04:34
  • Use [`shlex.split`](https://docs.python.org/3/library/shlex.html) first to tokenize the input string into an argument list, and then you should be able to use `argparse` as you normally would. – jamesdlin Nov 04 '21 at 04:35
  • The docs tell you [how to use `argparse` without `sys.argv`](https://docs.python.org/3/library/argparse.html#beyond-sys-argv). – Ken Y-N Nov 04 '21 at 04:42

2 Answers2

0

Here you go, in the below implementation the code is lengthy to be more descriptive and understandable, however once you understand the logic you can simplify it further.

Here I'm finding the index of url_identifier and data_identifier in the input_str, adding their respective lengths to find the index where they end and 1 for space character and then I'm slicing the input_str with the index data to get the required outputs.

def foo(input_str):
    url_identifier = "--url"
    data_identifier = "--data"
    
    url_identifier_start_idx = input_str.find(url_identifier)
    url_identifier_end_idx = url_identifier_start_idx + len(url_identifier) + 1

    data_identifier_start_idx = input_str.find(data_identifier)
    data_identifier_end_idx = data_identifier_start_idx + len(data_identifier) + 1

    url = input_str[url_identifier_end_idx:data_identifier_start_idx]

    data = input_str[data_identifier_end_idx:]

    print(url)
    print(data)

foo("--url google.com --data hello world")

OUTPUT

~/Rod-Cutting$ python hello.py 
google.com 
hello world
pranftw
  • 118
  • 1
  • 9
0

You can do this pretty easy with argparse. Split the input into an array and pass it to parse_args

import argparse

parser = argparse.ArgumentParser()
parser.add_argument("--url")
parser.add_argument("--data")

args = parser.parse_args(input('enter something here: ').split(' '))

print(f"{args.url=}")
print(f"{args.data=}")

Example with --url foo --data bar

enter something here: --url foo --data bar
args.url='foo'
args.data='bar'
flakes
  • 21,558
  • 8
  • 41
  • 88