-
Notifications
You must be signed in to change notification settings - Fork 0
/
,script
executable file
·94 lines (77 loc) · 2.79 KB
/
,script
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
#!/usr/bin/env python3
"""Creates an executable python script with a pre-filled shebang line and
optional `name == '__main__'` line.
"""
import argparse
import subprocess
import sys
import os
from pathlib import Path
from textwrap import dedent
parser = argparse.ArgumentParser()
parser.add_argument('file', help='The name of the script file to create')
parser.add_argument('lang', choices=['py', 'sh'],
help='The language in which the script will be written')
parser.add_argument('--main', action='store_true',
help="Adds the if __name__=='__main__' line")
parser.add_argument('-i', '--ignore', action='store_true',
help='Adds this script to a .gitignore file in the same directory')
parser.add_argument('--env', action='store_true',
help='Adds a shebang line that uses /usr/bin/env python3 instead\
of /usr/bin/python3')
parser.add_argument('--fn', help='Function prototype to add to the python file')
args = parser.parse_args()
file = args.file
ignore = args.ignore
lang= args.lang
def main():
# Don't overwrite files unless stated
if Path('.', file).exists():
overwrite = input(f'`{file}` already exists!\nOverwrite? (y/n): ')
if overwrite.strip().startswith('n'):
sys.exit('Okay. No files were changed! Bye!')
if lang == 'sh':
create_bash_script()
elif lang == 'py':
create_python_script()
else:
create_python_script()
# make file executable
print(f'{file} created successfully!')
os.chmod(file, S_IXUSR)
def add_to_gitignore():
subprocess.run(f'echo {file} >> .gitignore', shell=True)
ignore_message = '\nand added to .gitignore.'
print(f'`{file}` created successfully!{ignore_message}')
def create_python_script():
fn = str(args.fn) if args.fn else ''
shebang = '#!/usr/bin/env python3' if args.env else '#!/usr/bin/python3'
ellipsis_line = """..."""
if fn:
brackets = '()' if '(' not in fn else ''
# strip def and ending :
fn = fn.lstrip('def').rstrip(':').strip()
fn = dedent(f"""
def {fn}{brackets}:
{ellipsis_line}
""").strip()
name_line = """if __name__ == '__main__':
pass
""".strip() if args.main else ''
content = f"""
{shebang}
{fn}
{name_line}
""".strip()
command = f"""touch {file} \
&& echo "{content}" > {file} \
&& sudo chmod +x {file}
"""
subprocess.run(command, shell=True)
def create_bash_script():
content = """#!/usr/bin/env bash"""
with open(file, 'w', encoding='utf-8') as f:
f.write(content)
f.write("\n\n")
if __name__ == '__main__':
main()