Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- #! python3
- # newpy.py creates a new python file with corresponding batch file
- import os, sys
- from pathlib import Path
- from subprocess import Popen
- #preferred py file editor
- editor = Path('c:/') / 'Program Files' / 'Notepad++' / 'notepad++.exe'
- #preferred py files directory
- folder = Path.home() / 'PYTHON'
- def newpy(name, extension='py', path=folder):
- os.chdir(folder)
- if os.path.exists(name + '.' + extension):
- return print(f"WARNING: No file created.\n{name}.{extension} file already exists in this directory.")
- else:
- newFile = open(name + '.' + extension, 'a')
- newFile.write(f"#! python3\n# {name}.{extension} ")
- newFile.close()
- return print(f"'{name}.{extension}' created at {folder}.")
- def newbat(name, extension='py'):
- os.chdir(Path.home())
- if os.path.exists(name + '.bat'):
- return print("WARNING: No file created.\nA batch file with this name already exists in this directory.")
- else:
- newFile = open(name + '.bat', 'a')
- newFile.write(f"@{extension}.exe {folder}\\{name}.{extension} %*")
- if extension == 'py':
- newFile.write('\n@pause')
- newFile.close()
- return print(f"'{name}.bat' created for {folder}\\{name}.{extension}.")
- #invalid arguments
- if len(sys.argv) == 1:
- print("ERROR: No file created.\nThis script requires an argument for the new python file name.\nFor more information enter 'help' as first argument.")
- elif len(sys.argv) > 3:
- print("ERROR: No file created.\nThis script only accepts up to two arguments.\nFor more information enter 'help' as first argument.")
- elif sys.argv[1] == 'help':
- print(r"""DOCUMENTATION FOR newpy.py
- Author: thisduck (August 2020) u/thisduck_
- This script generates a new python file with opening shebang line and second line filename, along with a corresponding batch file for easy launching of the new script. Two arguments are accepted, but only the first is required.
- Argument 1: New python script filename
- Argument 2: File type (either 'py' or 'pyw')
- - optional;
- - omitting argument defaults to 'py'.
- """)
- #main execution
- else: #acceptable inputs
- filename = sys.argv[1]
- if len(sys.argv) > 2:
- if sys.argv[2] != 'py' and sys.argv[2] != 'pyw':
- print(f"CAUTION: Your chosen {sys.argv[2]} file extension may have unexpected results.")
- pytype = sys.argv[2]
- #write files
- newpy(filename, pytype)
- newFilePath = folder / f"{filename}.{pytype}"
- newbat(filename, pytype)
- else: #with default extension
- newpy(filename)
- newFilePath = folder / f"{filename}.py"
- newbat(filename)
- #open new file in editor
- Popen(f"{editor} {newFilePath}")
Add Comment
Please, Sign In to add comment