Skip to content

Navigation Menu

Sign in
Appearance settings

Search code, repositories, users, issues, pull requests...

Provide feedback

We read every piece of feedback, and take your input very seriously.

Saved searches

Use saved searches to filter your results more quickly

Appearance settings

Latest commit

 

History

History
History
executable file
·
194 lines (144 loc) · 5.16 KB

File metadata and controls

executable file
·
194 lines (144 loc) · 5.16 KB
Copy raw file
Download raw file
Open symbols panel
Edit and raw actions
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
185
186
187
188
189
190
191
192
193
194
#!/usr/bin/env python3
"""
Author : Ken Youens-Clark <kyclark@gmail.com>
Purpose: Python program to write a Python program
"""
import argparse
import os
import platform
import re
import subprocess
import sys
from datetime import date
from pathlib import Path
from typing import NamedTuple
class Args(NamedTuple):
program: str
name: str
email: str
purpose: str
overwrite: bool
# --------------------------------------------------
def get_args() -> Args:
"""Get arguments"""
parser = argparse.ArgumentParser(
description='Create Python argparse program',
formatter_class=argparse.ArgumentDefaultsHelpFormatter)
defaults = get_defaults()
username = os.getenv('USER') or 'Anonymous'
hostname = os.getenv('HOSTNAME') or 'localhost'
parser.add_argument('program', help='Program name', type=str)
parser.add_argument('-n',
'--name',
type=str,
default=defaults.get('name', username),
help='Name for docstring')
parser.add_argument('-e',
'--email',
type=str,
default=defaults.get('email', f'{username}@{hostname}'),
help='Email for docstring')
parser.add_argument('-p',
'--purpose',
type=str,
default=defaults.get('purpose', 'Rock the Casbah'),
help='Purpose for docstring')
parser.add_argument('-f',
'--force',
help='Overwrite existing',
action='store_true')
args = parser.parse_args()
args.program = args.program.strip().replace('-', '_')
if not args.program:
parser.error(f'Not a usable filename "{args.program}"')
return Args(args.program, args.name, args.email, args.purpose, args.force)
# --------------------------------------------------
def main() -> None:
"""Make a jazz noise here"""
args = get_args()
program = args.program
if os.path.isfile(program) and not args.overwrite:
answer = input(f'"{program}" exists. Overwrite? [yN] ')
if not answer.lower().startswith('y'):
sys.exit('Will not overwrite. Bye!')
print(body(args), file=open(program, 'wt'), end='')
if platform.system() != 'Windows':
subprocess.run(['chmod', '+x', program], check=True)
print(f'Done, see new script "{program}."')
# --------------------------------------------------
def body(args: Args) -> str:
""" The program template """
today = str(date.today())
return f"""#!/usr/bin/env python3
\"\"\"
Author : {args.name}{' <' + args.email + '>' if args.email else ''}
Date : {today}
Purpose: {args.purpose}
\"\"\"
import argparse
# --------------------------------------------------
def get_args():
\"\"\"Get command-line arguments\"\"\"
parser = argparse.ArgumentParser(
description='{args.purpose}',
formatter_class=argparse.ArgumentDefaultsHelpFormatter)
parser.add_argument('positional',
metavar='str',
help='A positional argument')
parser.add_argument('-a',
'--arg',
help='A named string argument',
metavar='str',
type=str,
default='')
parser.add_argument('-i',
'--int',
help='A named integer argument',
metavar='int',
type=int,
default=0)
parser.add_argument('-f',
'--file',
help='A readable file',
metavar='FILE',
type=argparse.FileType('rt'),
default=None)
parser.add_argument('-o',
'--on',
help='A boolean flag',
action='store_true')
return parser.parse_args()
# --------------------------------------------------
def main():
\"\"\"Make a jazz noise here\"\"\"
args = get_args()
str_arg = args.arg
int_arg = args.int
file_arg = args.file
flag_arg = args.on
pos_arg = args.positional
print(f'str_arg = "{{str_arg}}"')
print(f'int_arg = "{{int_arg}}"')
print('file_arg = "{{}}"'.format(file_arg.name if file_arg else ''))
print(f'flag_arg = "{{flag_arg}}"')
print(f'positional = "{{pos_arg}}"')
# --------------------------------------------------
if __name__ == '__main__':
main()
"""
# --------------------------------------------------
def get_defaults():
"""Get defaults from ~/.new.py"""
rc = os.path.join(str(Path.home()), '.new.py')
defaults = {}
if os.path.isfile(rc):
for line in open(rc):
match = re.match('([^=]+)=([^=]+)', line)
if match:
key, val = map(str.strip, match.groups())
if key and val:
defaults[key] = val
return defaults
# --------------------------------------------------
if __name__ == '__main__':
main()
Morty Proxy This is a proxified and sanitized view of the page, visit original site.