0

I have the below python snippet

@click.argument('file',type=click.Path(exists=True))

The above command read from a file in the below format

python3 code.py file.txt

The same file is processed using a function

def get_domains(domain_names_file):
    with open(domain_names_file) as f:
        domains = f.readlines()
    return domains
domains = get_domains(file)

I dont want to read it from file , I want to provide a domain as an argument while executing in terminal , the command will be

python3 code.py example.com

How should I rewrite the code .

Python Version : 3.8.2

3
  • 1
    Look into argparse. Commented Jul 22, 2020 at 8:49
  • 2
    Remove the type from the argument declaration. See docs Commented Jul 22, 2020 at 8:49
  • @rdas can you make an answer Commented Jul 22, 2020 at 8:51

3 Answers 3

3

I realised you're using the click library. Since you want to pass the 'domain'/website as an argument, you can just input it as a string. If you remove the 'type' parameter from your decorator, it would make the type STRING by default.

The most basic option is a simple string argument of one value. If no type is provided, the type of the default value is used, and if no default value is provided, the type is assumed to be STRING.

Solution: @click.argument('domain')

Sign up to request clarification or add additional context in comments.

Comments

1

click.argument by default creates arguments that are read from the command line:

@click.argument('file')

This should create an argument that is read from the command line and made available in the file argument.

See the docs & examples here

2 Comments

changing it into @click.argument() , will work ? I couldnt understand
Yes. The type that you're passing enforces that the value is a valid file path. If you want to read the data directly, you can remove that. see the example here: pocoo-click.readthedocs.io/en/latest/arguments/#basic-arguments
0

You may use argparse:

import argparse

# set up the different arguments
parser = argparse.ArgumentParser(description='Some nasty description here.')
parser.add_argument("--domain", help="Domain:   www.some-domain.com", required=True)

args = parser.parse_args()
print(args.domain)

And you invoke it via

python your-python-file.py --domain www.google.com

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.