Skip to content

Instantly share code, notes, and snippets.

@NeuronQ
Created April 24, 2017 21:05
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 NeuronQ/2f4f7f2d4c38145a1df6cd2393486141 to your computer and use it in GitHub Desktop.
Save NeuronQ/2f4f7f2d4c38145a1df6cd2393486141 to your computer and use it in GitHub Desktop.
Boilerplate for writing "shell-like" Python scripts
#!/usr/bin/env python
# both python 2 and 3 comatible
from __future__ import absolute_import, division, print_function, unicode_literals
try:
input = raw_input
except NameError:
pass
import sys
import os
import pwd
import argparse
from subprocess import call
# when in debug mode, just pretend to do stuff
# (output shell commands with "~" prefix)
DEBUG = False
arg_parser = argparse.ArgumentParser()
arg_parser.add_argument('--absPath', required=True)
arg_parser.add_argument('--wpUrl')
args = arg_parser.parse_args()
if not args.setupUser:
args.setupUser = 'some user'
def do(str):
"""execute string command after replacing args in it"""
str = str.format(**vars(args))
print('\n~ ' + str)
if DEBUG:
return
return call(str, shell=True)
def user_do(str):
"""
execute command as user (useful when script needs to run as sudo, but
some of the commands need to be un as a username given by argument --user)
"""
do('sudo -u {} {}'.format(args.setupUser, str))
def require(cond):
"""stop execution if a condition is not satisfied"""
if not cond:
print("Abandoning...")
sys.exit(1)
def confirm(str, defaultYes=True):
"""ask user for confirmation"""
str += " " + ("[Y/n]" if defaultYes else "[y/N]")
r = input(str) or 'y'
require(r.strip().lower() == 'y')
print(
"""Will use:
absPath: {absPath}
user: {user}
homeUrl: {homeUrl}
urlPath: {urlPath}
wpUrl: {wpUrl}
db: {db}
dbUser: {dbUser}
dbPwd: {dbPwd}
""".format(**vars(args))
)
confirm("Does this seem OK?")
# do somehting if a user exists and somehting else if it soes not
try:
pwd.getpwnam(args.user)
# user exists:
# ...
except KeyError:
# user does not exist (maybe create it?)
# ...
pass
# ugly way to do mysql commands
# (keep one per line to continue despite errors)
do("""mysql <<EOF
CREATE USER USER IF NOT EXISTS '{dbUser}'@'localhost' IDENTIFIED BY '{dbPwd}';
EOF""")
# either cat-in or file operations, whatever one prefers...
do('cat <<EOF >> /etc/nginx/sites-available/_wps_lab.neuronq.ro\n' +
nginx_conf + '\nEOF')
# with open('/home/neuronq/lab.neuronq.ro/etc/nginx.conf', 'a+') as f:
# f.wite(nginx_conf)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment