Run Python Script on Selected File

前端 未结 4 1084
星月不相逢
星月不相逢 2020-12-07 17:57

I would like to write a python script that would upload any file I select in Windows Explorer. The idea is to select any file in Windows Explorer, right-click to display fil

相关标签:
4条回答
  • 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.

    0 讨论(0)
  • 2020-12-07 18:39

    Instead of %1 use %*.

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

    @echo off
    cls
    python 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

    0 讨论(0)
  • 2020-12-07 18:49

    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 off
    cls
    python 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 sys
    sys.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 off
    cls
    :upload_loop
    IF "%1"=="" GOTO completed
      python C:\Your\File\uploadscript.py %1
      SHIFT
      GOTO upload_loop
    :completed
    
    0 讨论(0)
  • 2020-12-07 18:53

    This webpage Adding Windows context-menu actions has a nice python script that will register a context menu to pass the file path to your python script. I have not tried but it looks easy to modify this sample to what you need to do. Plus, this way it is one click less than sendTo solution I guess.

    0 讨论(0)
提交回复
热议问题