Run Python Script on Selected File Run Python Script on Selected File windows windows

Run Python Script on Selected File


Assuming Windows 7, If you open a folder and type "shell:sendto" in the address bar then hit enter you'll be taken to the context menu. You can add a .cmd file with the following in it.

@echo offclspython C:\Your\File\uploadscript.py %1

This should execute your python script passing in the file (%1) as a parameter. Within the python script you can use:

import syssys.argv  #sys.argv[1] is the file to upload

This gets all parameters passed in so sys.argv[1] should get you the file that was passed in. I tested this and it works. The reason you need the .cmd file instead of going right to the .py is because the .py file wont show up in the Send To menu.

More information on getting the file passed in is here:
Accepting File Argument in Python (from Send To context menu)

EDIT: Adding script for calling on multiple files. Note this calls the python script on each individual file, if you want to send all the files as a parameter to the python script then you'll need to do a bit more work. You need to research batch scripting if you want to do more advanced things.

@echo offcls:upload_loopIF "%1"=="" GOTO completed  python C:\Your\File\uploadscript.py %1  SHIFT  GOTO upload_loop:completed


Instead of %1 use %*.

%1 will pass in the first argument, %* will pass all (%n will pass in the nth...)

@echo offclspython C:\Your\File\uploadscript.py %*

Note that the command line has built in character limits 2047 for XP and prior, 8191 for windows 7 and later


To add things such as python scripts to right click context menu, also possible is to add register keys (regedit) in

\HKEY_CLASSES_ROOT\Directory\Background\shell

There, add a container, name it the string you want to appear in the context menu. In it, add a key of type REG_SZ, which contains the python script launcher for instance

C:\Python27\python.exe "C:\path\to\your\script\yourscript.py"

I do not know how to make that work with the aforementionned solution for getting multiple file selections into sys.argv, but I thought this would me worth mentioning here as well.