Skip to content

Instantly share code, notes, and snippets.

@xezpeleta
Last active November 3, 2015 08:34
Show Gist options
  • Save xezpeleta/c4fa30ae6a1720de5abb to your computer and use it in GitHub Desktop.
Save xezpeleta/c4fa30ae6a1720de5abb to your computer and use it in GitHub Desktop.
Set up Google Analytics web tracking code
#! /usr/bin/python
'''
Python script to set up GA web tracking code, usually in static web files (in PHP files, you can use a simple 'include' or 'require_once').
add_ga_code.py <file> <track-id>
Example: add_ga_code.py /var/www/index.html UA-557744-10
To add the tracking code in multiple files, use a oneliner. Example:
grep -r 'analytics' --include=*.html -L /var/www/ | xargs -L 1 -i /root/scripts/add_ga_code.py {} UA-557744-10
'''
import sys
import shutil
import os
def trackcode(trackid):
trackcode = """
<script>
(function(i,s,o,g,r,a,m){i['GoogleAnalyticsObject']=r;i[r]=i[r]||function(){
(i[r].q=i[r].q||[]).push(arguments)},i[r].l=1*new Date();a=s.createElement(o),
m=s.getElementsByTagName(o)[0];a.async=1;a.src=g;m.parentNode.insertBefore(a,m)
})(window,document,'script','//www.google-analytics.com/analytics.js','ga');
ga('create', '%s', 'auto');
ga('send', 'pageview');
</script>
""" % (trackid)
return trackcode
def endhead_line(path):
lookup = '</head>'
with open(path) as f:
for n, line in enumerate(f, 1):
if lookup in line:
return n-1
def backup_file(path):
shutil.copyfile(path, path+".bak")
if os.path.isfile(path+".bak"):
#print "Duplicating file to %s.bak... OK!" % (path)
return True
else:
print "Duplicating file to %s.bak... ERROR!" % (path)
return False
def insert_analytics(path, trackid):
index = endhead_line(path)
value = trackcode(trackid)
f = open(path, "r")
contents = f.readlines()
f.close()
contents.insert(index, value)
f = open(path, "w")
contents = "".join(contents)
f.write(contents)
f.close
return True
if __name__ == '__main__':
app = sys.argv[0]
args = sys.argv[1:]
if len(args) == 2:
path = args[0]
trackid = args[1]
else:
print "Usage: %s file trackid" % (app)
exit(1)
if backup_file(path):
if insert_analytics(path, trackid):
print "File %s: OK!" % (path)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment