Question

I'm trying to create a command line interface for the dft.ba URL shortener using python's argparse and a function in .profile which calls my python script. This is the business end of the code in my python script:

parser = argparse.ArgumentParser(description='Shortens URLs with dft.ba')
parser.add_argument('LongURL',help='Custom string at the end of the shortened URL')
parser.add_argument('--source','-s',help='Custom string at the end of the shortened URL')
parser.add_argument('-c','--copy', action="store_true", default=False, help='Copy the shortened URL to the clipboard')
parser.add_argument('-q','--quiet', action="store_true", default=False, help="Execute without printing")
args = parser.parse_args()
target_url=args.LongURL
source=args.source
print source


query_params={'auth':'ip','target':target_url,'format':'json','src':source}
shorten='http://dft.ba/api/shorten'
response=requests.get(shorten,params=query_params)
data=json.loads(response.content)
shortened_url=data['response']['URL']
print data
print args.quiet
print args.copy

if data['error']:
    print 'Error:',data['errorinfo']['extended']
elif not args.copy:
    if args.quiet:
        print "Error: Can't execute quietly without copy flag"
    print 'Link:',shortened_url
else:
    if not args.quiet:
        print 'Link:',shortened_url
        print 'Link copied to clipboard'
    setClipboardData(shortened_url)

and then in .profile I have this:

dftba(){
    cd ~/documents/scripts
    python dftba.py "$1" 
}

running dftba SomeURL will spit a shortened URL back at me, but none of the options work.When I try to use -s SomeSource before the LongURL, it gives error: argument --source/-s: expected one argument, when used afterwards it does nothing and when omitted gives error: too few arguments. -c and -q give error: too few arguments for some reason. The copy to clipboard function I'm using works perfectly fine if I force copying, however.

I'm very much feeling my way through this, so I'm sorry if I've made some glaringly obvious mistake. I get the feeling the problem's in my bash script, I just don't know where.

Any help would be greatly appreciated. Thank you.

Was it helpful?

Solution

Lets just focus on what the parser does

parser = argparse.ArgumentParser(description='Shortens URLs with dft.ba')
parser.add_argument('LongURL',help='Custom string at the end of the shortened URL')
parser.add_argument('--source','-s',help='Custom string at the end of the shortened URL')
parser.add_argument('-c','--copy', action="store_true", default=False, help='Copy the shortened URL to the clipboard')
parser.add_argument('-q','--quiet', action="store_true", default=False, help="Execute without printing")
args = parser.parse_args()
print args  # add to debug the `argparse` behavior

LongURL is a positional argument that is always required. If missing you'll get the 'too few arguments' error message.

source is optional, but when provided must include an argument. If not given args.source is None. As written the source argument must be given in ADDITION to the LongURL one.

Both args.copy and args.quiet are booleans; default value is False; and True if given. (the default=False parameter is not needed.)

I haven't tried to work through the logic using copy and quiet. That won't come into play if there are problems earlier with LongURL and source.

Compare these samples:

In [38]: parser.parse_args('one'.split())
Out[38]: Namespace(LongURL='one', copy=False, quiet=False, source=None)

In [41]: parser.parse_args('-s one two -c -q'.split())
Out[41]: Namespace(LongURL='two', copy=True, quiet=True, source='one')

It may also help to look at what parse_args is parsing: sys.argv[1:] (if you have doubts about what you are getting from .profile).

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top