Reputation: 1398
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
Upvotes: 0
Views: 503
Reputation: 431
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')
Upvotes: 3
Reputation: 21275
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
Upvotes: 1
Reputation: 43169
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
Upvotes: 0