Skip to content

Instantly share code, notes, and snippets.

@jkyeung
Created July 13, 2022 16:16
Show Gist options
  • Save jkyeung/f4f8e4db6322e77e9c9169886eb5efef to your computer and use it in GitHub Desktop.
Save jkyeung/f4f8e4db6322e77e9c9169886eb5efef to your computer and use it in GitHub Desktop.
Generate a .bat file to use for invoking a Python script
@echo off
cls
if %1. == . goto error
if not %2. == . goto error
python "%~dp0/create_bat_wrapper.py" %1
goto exit
:error
echo Drop exactly one file onto my icon.
:exit
echo;
pause > nul | set /p =Press any key to exit...
import sys
import os
# A batch file can have at most nine arguments.
numwords = [
'zero', 'one', 'two', 'three', 'four',
'five', 'six', 'seven', 'eight', 'nine']
py_name = sys.argv[1]
root, ext = os.path.splitext(py_name)
if ext not in {'.py', '.pyw'}:
sys.exit("Input file doesn't look a Python script; aborting.")
bat_name = root + '.bat'
while True:
try:
args = int(input('How many arguments? '))
if args in range(10):
break
except ValueError:
pass
print('> Must be an integer between 0 and 9.')
path_spec = None
while path_spec not in {'a', 'abs', 'absolute', 'r', 'rel', 'relative'}:
path_spec = input('Absolute or relative script directory? ').lower()
script_name = {
'a': py_name,
'r': os.path.join('%~dp0', os.path.basename(py_name))
}[path_spec[0]]
print(f'> Script will be specified as: "{script_name}"')
with open(bat_name, 'w') as f:
f.write('@echo off\ncls\n')
for i in range(args):
f.write(f"if %{i + 1}. == . goto error\n") # argument cannot be empty
f.write(f"if not %{args + 1}. == . goto error\n") # cannot pass extra arguments
f.write(f'\npython "{script_name}"')
for i in range(args):
f.write(f" %{i + 1}")
f.write('\ngoto exit\n')
f.write(f"\n:error\necho Drop exactly {numwords[args]} ")
f.write(('file' if args == 1 else 'files') + ' onto my icon.\n')
f.write('\n:exit\necho;\npause > nul | set /p =Press any key to exit...\n')
print('Done.')
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment