python command line arguments, how to pass argument as value for script

Question:

I am having a hard time passing the arguments as value for my script in python. Here’s my code:

import request, json, sys

def main():
    url = 'https://jsonplaceholder.typicode.com/posts'
    r = requests.get(url)
    data = json.loads(r.text)


    if len(sys.argv) != 3:
        print("Usage must equal [userId] [postId]")
        exit()
    for user in data:
        if user['userId'] == sys.argv[1] and user['id'] == sys.argv[2]:
            print('here i am')
            print(user)

if __name__ == "__main__":
    main()

When I run python -m test 1 1, nothing happens. But it does trigger when I don’t have enough arguments or too many.

Asked By: user2816227

||

Answers:

The problem is that command line arguments are strings and the data you seek are integers. You could convert arg[1] and arg[2] to integers or you could use the argparse module to build a more comprehensive command line parser.

import requests, json, sys, argparse

def main():
    parser = argparse.ArgumentParser(description='Do all the things')
    parser.add_argument('user_id', type=int,
                    help='the user id')
    parser.add_argument('id', type=int,
                    help='the other id')
    args = parser.parse_args()

    url = 'https://jsonplaceholder.typicode.com/posts'
    r = requests.get(url)
    data = json.loads(r.text)
    
    for user in data:
        if user['userId'] == args.user_id and user['id'] == args.id:
            print('here i am')
            print(user)

if __name__ == "__main__":
    main()
Answered By: tdelaney