Skip to content

Instantly share code, notes, and snippets.

@benjchristensen
Created October 13, 2011 17:14
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save benjchristensen/1284836 to your computer and use it in GitHub Desktop.
Save benjchristensen/1284836 to your computer and use it in GitHub Desktop.
Shell script with command line arguments
#!/usr/bin/env python
import subprocess
import argparse
import zipfile
import os
parser = argparse.ArgumentParser(description='Upload a file or files to a RESTful endpoint')
parser.add_argument('-e', '--environment', metavar='TEST/PROD',
help='The environment to upload to: TEST/PROD')
parser.add_argument('--host', metavar='host:port',
help='If a specific host rather than environment is desired.')
parser.add_argument('someMetadata', metavar='SomeMetadataWithFile',
help='Some type of metadata to send with the file')
parser.add_argument('file', metavar='File', nargs='*',
help='the file to upload')
args = parser.parse_args()
#print args
def uploadFile(filename):
# get hostname
url = "http://"
if args.host != None:
url += args.host
else:
if args.environment == 'PROD':
url += "PROD_URL_GOES_HERE"
elif args.environment == 'TEST':
url += "TEST_URL_GOES_HERE"
# append the rest of the URL and action
url += "/restfulEndpointHere?action=UPLOAD"
# append the someMetadata field
url += "&someMetadata=" + args.someMetadata
# upload file
print "Uploading to " + url + " ..."
print ""
subprocess.call(['curl', '--data-binary', '@'+filename, '-w', '\n', url])
if len(args.file) == 1:
print "Uploading single file: %s" % args.file[0]
uploadFile(args.file[0])
else:
print "Combining multiple files as zip:"
# create the zip file
zipPath = "./.upload.zip"
file = zipfile.ZipFile(zipPath, "w")
for filename in args.file:
print " " + filename
file.write(filename, os.path.basename(filename), zipfile.ZIP_DEFLATED)
file.close()
uploadFile(zipPath)
os.remove(zipPath)
@benjchristensen
Copy link
Author

This is an example for my records of creating a command line shell with argument parsing.

It's written in Python instead of bash as Python was far nicer to work with for this and it's available on virtually every *nix installation so is almost as equally portable.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment