/
pytemplate
executable file
·184 lines (145 loc) · 6.17 KB
/
pytemplate
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
#!/usr/bin/env python
# title : pytemplate
#description : This will create a python file from a template, and optionally
# create a git repo for it.
#author : Dayo Adewunmi
#date : 20130113
#version : 1.0
#notes :
#license : GNU GPL3 http://www.gnu.org/licenses/
#python_version : 2.6.6
#==============================================================================
# Import the modules needed to run the script.
import ConfigParser
from optparse import OptionParser
from os.path import exists
from time import strftime
import os
import shutil
import subprocess
import sys
def createConfigFile():
""" Prompt for configuration options and write them to ~/.pytemplate.conf. """
config = ConfigParser.ConfigParser()
# Prompt for author name
author = raw_input("Enter your name: ")
# Prompt for author email address
authoremail = raw_input("Enter your email address: ")
config.add_section("author")
config.set("author", "author", author)
config.set("author", "email", authoremail)
licensinginfo = raw_input("Enter the python file's licensing information: ")
config.add_section("license")
config.set("license", "license", licensinginfo)
# Write it all to config file
with open(os.getenv('HOME') + '/.pytemplate.conf', 'wb') as configfile:
config.write(configfile)
return config
def createPyFile(repo=0):
""" When user doesn't provide a value, read from config file and
write to python file, else use the values provided user."""
# Get config file
config = ConfigParser.ConfigParser()
config.read(os.getenv('HOME') + '/.pytemplate.conf')
# Prompt for filename of the python file.
# filename is required, so keep prompting until it is provided.
filename = ''
while filename == '':
filename = raw_input("Please enter a filename for your python file: ")
# Check if filename already exists, if it does, reset the filename variable.
if exists(filename):
print "\nFile already exists. Please use a different filename."
filename = ''
# If requested, first create the git repo and point the path
# to the repo's 'public' directory.
destdir = os.getcwd()
if repo:
reponame = os.path.splitext(filename)[0]
destdir = createGitRepo(reponame)
# Open python file with pre-configured values
pyfile = os.path.abspath(destdir) + "/" + filename
pyfileObj = open(pyfile, "w")
# Write the shebang line
pyfileObj.write('#!/usr/bin/env python' + '\n')
# Write the filename
pyfileObj.write('# filename: ' + filename + '\n')
pyfileObj.write('# description: ')
# Prompt for optional python file description.
filedescription = raw_input("Enter a description for your python file: ")
if filedescription != '':
pyfileObj.write(filedescription + '\n')
else:
pyfileObj.write('\n')
# Prompt for the optional python file's version number.
pyfileObj.write('# fileversion: ')
fileversion = raw_input("Enter the python file's version number: ")
if fileversion != '':
pyfileObj.write(fileversion + '\n')
else:
pyfileObj.write('\n')
# Auto-generate and add date of file creation
pyfileObj.write('# date: ' + strftime("%Y%m%d") + '\n')
# Prompt for author's name...
author = raw_input("Enter author's name: ")
if author != '':
pyfileObj.write('# author: ' + author + '\n')
# ...or use author's name from config file.
else:
pyfileObj.write('# author: ' + config.get("author", "author") + '\n')
# Prompt for author's email address...
email = raw_input("Enter author's email address: ")
if email != '':
pyfileObj.write('# email: ' + email + '\n')
# ...or use author's email address from config file.
else:
pyfileObj.write('# email: ' + config.get("author", "email") + '\n')
# Prompt for license type...
license = raw_input("Enter license type [%s]: " %(config.get("license", "license")))
if license != '':
pyfileObj.write('# license: ' + license + '\n')
# ...or use license type from config file.
else:
pyfileObj.write('# license: ' + config.get("license", "license") + '\n')
# Auto-add python version
python_version = sys.version[:5] # This will spit out a bunch of other info, so slice it
pyfileObj.write('# python version: ' + python_version + '\n')
# Also an empty main() definition
pyfileObj.write('\n\n\n\n')
pyfileObj.write('def main():' + '\n')
pyfileObj.write(" print \'\'" + '\n\n')
pyfileObj.write('if __name__ == \"__main__\":' + '\n')
pyfileObj.write(' main()')
# Change file permissions to Make the python file executable
os.chmod(pyfile, 0755)
pyfileObj.close()
# Open newly created and populated python file in default text editor
myeditor = os.environ["EDITOR"] + " %s" %pyfile
os.system(myeditor)
exit()
def createGitRepo(justpyfilename):
""" Create a git repo for the python file with the same name as the python file. """
repoPath = os.path.abspath(justpyfilename)
subprocess.call(["mkdir", repoPath])
subprocess.call(["mkdir", repoPath + "/public"])
subprocess.call(["mkdir", repoPath + "/doc"])
subprocess.call(["touch", repoPath + "/doc/README"])
repoPublicPath = repoPath + "/public"
return repoPublicPath
def main():
# Command line parameters
usage = "Usage: %prog [options] arg"
parser = OptionParser(usage)
parser.add_option("-c", "--config", dest="config_file", action="store_true", help="configure pytemplate")
parser.add_option("-g", "--git-repo", dest="git_repo", action="store_true", help="create a git repo for this file")
(options, args) = parser.parse_args()
# Does user want to configure pytemplate?
if options.config_file:
createConfigFile()
# Or, does user also wants a git repo created for the python file?
elif options.git_repo:
createPyFile(1)
# Default is to use options from config file and from user input to create a new python file.
else:
createPyFile()
if __name__ == "__main__":
main()