Una forma simple e intuitiva de agregar sus scripts personalizados a sus Windows Haga clic derecho con contexmenu.
Puede descargar el archivo pywin_contextmenu.py de este repositorio (https://raw.githubusercontent.com/naveennamani/pywin_contextmenu/master/pywin_contextmenu.py) y coloque el archivo en su carpeta de scripts.
O puede instalar este paquete desde Pypi usando
pip install pywin-contextmenuy simplemente importe en sus scripts.
import pywin_contextmenu as pycm import pywin_contextmenu as pycm
# create a group
group1 = pycm . ContextMenuGroup ( "My python scripts" )
# convert your script into executable command
script_cmd = pycm . python_script_cmd ( "scripts/clean_empty_folders.py" , rel_path = True , hide_terminal = True )
# create the item
item1 = pycm . ContextMenuItem ( "Clean empty folders" , script_cmd )
# add item to the group
group1 . add_item ( item1 )
# or
group1 . add_items ([ item1 ])
# get root_key
rk = pycm . get_root ( pycm . UserType . CURR_USER , pycm . RootType . DIR_BG )
# Create the group and test
group1 . create ( rk )
########################
# In a more pythonic way
########################
pycm . ContextMenuGroup ( "Group 1" , items = [
pycm . ContextMenuItem ( "Open CMD" , "cmd.exe" ),
pycm . ContextMenuItem ( "Open CMD 2" , "cmd.exe" )
]). create (
pycm . get_root ( pycm . UserType . CURR_USER , pycm . RootTYpe . DIR_BG )
) import pywin_contextmenu as pycm
def test_function ( file_or_dir_name ):
print ( file_or_dir_name )
input ( "Press ENTER to continue" )
# create the nested groups to execute direct commands, python functions
# and python scripts
cmgroup = pycm . ContextMenuGroup ( "Group 1" , items = [
pycm . ContextMenuItem ( "Open cmd" , "cmd.exe" ),
pycm . PythonContextMenuItem ( "Test py" , test_function ),
pycm . ContextMenuGroup ( "Group 2" , items = [
pycm . PythonContextMenuItem ( "Python script test" , pycm . python_script_cmd (
"example.py" , rel_path = True , hide_terminal = True
))
])
])
# create the group for the current user to be shown on right click of
# directory, directory background and for python files
cmgroup . create_for ( pycm . UserType . CURR_USER , [
pycm . RootType . DIR ,
pycm . RootType . DIR_BG ,
pycm . RootType . FILE . format ( FILE_TYPE = ".py" )
]) El script depende de dos clases principales ContextMenuItem y ContextMenuGroup .
ContextMenuItemEste es el elemento de menú que activa y inicia el comando cuando se hace clic en el contextMenu. La firma de esta clase es
ContextMenuItem (
item_name , # name of the item to be shown
command , # command to be executed when selected
item_reg_key = "" , # registry key associated with the item
# (if not given will be treated as item_name)
icon = "" , # path to an icon to be shown with the item
extended = False # set to True if the item is to be shown when right clicked with shift button
) .create(root_key: HKEYType) : agrega el elemento al registro en el registro dado root_key . Obtenga el método de utilidad get_root Usando root_key .
.create_for(user_type: UserType, root_type: List[RootType]) - Agrega los elementos para ubicaciones de usuario y raíz dadas.
.delete(root_key: HKEYType) - elimine el elemento en el root_key dado.
.delete_for(user_type: UserType, root_type: List[RootType]) - Elimine los elementos para el usuario y las ubicaciones raíz.
.delete no se prefiere ya que se puede pasar cualquier root_key . En su lugar, use el método .delete_for ya que las claves de registro para eliminar se eliminarán automáticamente y de manera segura.PythonContextMenuItem Esta clase hereda ContextMenuItem y convierte una función de Python en un comando ejecutable. Simplemente pase la función de Python como argumento python_function .
PythonContextMenuItem (
item_name ,
python_function : Callable [[ str ], Any ], # callable python function which should take file/folder name as the single argument
item_reg_key = "" ,
icon = "" ,
extended = False
)ContextMenuGroupEsta clase agrupa múltiples elementos y subgrupos.
ContextMenuGroup (
group_name , # name of the group to be shown
group_reg_key = "" , # registry key associated with the group
icon = "" , # path to an icon to be shown with the group
extended = False , # set to True if the group is to be shown when right clicked with shift button
items = [] # items to be displayed on this group
) Para agregar elementos o grupos a una instancia de grupo, llame add_item / add_items método de la clase.
ContextMenuGroup . add_item ( item )
# or
ContextMenuGroup . add_item ( subgroup )
# for multiple items
ContextMenuGroup . add_items ([ item1 , item2 , subgroup1 , subgroup2 ])ContextMenuGroup al pasar los elementos usando la palabra clave de items . Luego, para crear el grupo y agregar al contextMenu, simplemente llame .create con la clave obtenida de la función get_root como argumento.
ContextMenuGroup.create(root_key) # Create the group and add to contextmenu
La clase también tiene método .create , .create_for , .delete y .delete_for métodos que son los mismos que los de los métodos de ContextMenuItem .
ContextMenuItem y ContextMenuGroup se devuelven self , por lo que pueden ser encadenados. Agregar elementos a ContextMenuGroup no los agregará al contextMenu/registro a menos .create se llame al método. RootType : una Enum para elegir dónde se mostrará el elemento/grupo del menú contextualUserType : un Enum para elegir si se debe agregar el menú contextual para el usuario actual o para todos los usuariosget_root(user_type: UserType, root_type: RootType, file_type: str) - crea/abre la clave de registro para el user_type y root_type seleccionado. Si el root_type es RootType.FILE , entonces se requiere argumento file_type e indica la extensión del archivo.python_script_cmd(script_path, rel_path = False, hide_terminal = False) - una función de utilidad para convertir un script_path dado a un comando ejecutable.delete_item(root_key, item_reg_key) - elimina el item_reg_key en el registro root_key dado. Advertencia: asegúrese de no eliminar las teclas en las teclas de registro de nivel superior (por ejemplo, HKEY_CLASSES_ROOT , HKEY_CURRENT_USER ETC.)