1

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.

11
  • 1
    What is the problem with your code? Maybe you need to convert the data types of the arguments to match those in the user dict? Commented Oct 18, 2022 at 19:17
  • You don't call main so no code runs. Commented Oct 18, 2022 at 19:19
  • @tdelaney I wanted to keep it short, I guess I assumed that everyone knows that main is in there Commented Oct 18, 2022 at 19:21
  • 2
    If you are using 2 command line args, and they don't match any values in the data dict, then nothing is supposed to happen Commented Oct 18, 2022 at 19:24
  • 1
    @alvaroavila I am getting an empty result. But that wasn't what I was looking for. If I hard code all the values. Then everything in the user variable prints out. I guess I need to work on my explanations better. But what I was looking for is something tdelaney has. Commented Oct 18, 2022 at 21:04

1 Answer 1

2

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()
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.