Uma maneira simples e intuitiva de adicionar seus scripts personalizados ao seu Windows Right Click ContextMenu.
Você pode baixar o arquivo pywin_contextmenu.py deste repositório (https://raw.githubusercontent.com/naveennamani/pywin_contextmenu/master/pywin_contextmenu.py) e colocar o arquivo na pasta Scripts.
Ou você pode instalar este pacote a partir de Pypi usando
pip install pywin-contextmenue simplesmente importar em seus 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" )
]) O script depende de duas classes principais ContextMenuItem e ContextMenuGroup .
ContextMenuItemEste é o item de menu que aciona e inicia o comando quando clicado no Menu do contexto. A assinatura desta classe é
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) - adiciona o item ao registro no registro especificado root_key . Obtenha o root_key usando o método get_root utilitário.
.create_for(user_type: UserType, root_type: List[RootType]) - adiciona os itens para o usuário determinado e os locais raiz.
.delete(root_key: HKEYType) - Exclua o item no root_key fornecido.
.delete_for(user_type: UserType, root_type: List[RootType]) - exclua os itens para o usuário fornecido e os locais raiz.
.delete não é preferido, pois qualquer root_key pode ser passado. Em vez disso, use .delete_for Método Como as chaves do registro a serem excluídos serão excluídos automaticamente e com segurança.PythonContextMenuItem Esta classe herda ContextMenuItem e converte uma função python em um comando executável. Basta passar na função 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 classe agrupa vários itens e 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 adicionar itens ou grupos a uma instância do grupo CHAMADA add_item / add_items Método da classe.
ContextMenuGroup . add_item ( item )
# or
ContextMenuGroup . add_item ( subgroup )
# for multiple items
ContextMenuGroup . add_items ([ item1 , item2 , subgroup1 , subgroup2 ])ContextMenuGroup , passando os itens usando a palavra -chave de items . Em seguida, para criar o grupo e adicionar ao contexto Menu simplesmente chamar .create com a chave obtida da função get_root como argumento.
ContextMenuGroup.create(root_key) # Create the group and add to contextmenu
A classe também possui métodos .create , .create_for , .delete e .delete_for métodos que são os mesmos dos métodos de ContextMenuItem .
ContextMenuItem e ContextMenuGroup self , para que possam ser acorrentados. Adicionar itens ao ContextMenuGroup não os adicionará ao contexto/registro, a menos que o método .create seja chamado. RootType - uma Enum para escolher onde o item/grupo de menu de contexto será exibidoUserType - um Enumget_root(user_type: UserType, root_type: RootType, file_type: str) - cria/abre a chave do registro para o user_type selecionado e root_type. Se o root_type for RootType.FILE , o argumento file_type for necessário e indicar a extensão do arquivo.python_script_cmd(script_path, rel_path = False, hide_terminal = False) - uma função de utilidade para converter um determinado script_path em um comando executável.delete_item(root_key, item_reg_key) - Exclui o item_reg_key no registro root_key fornecido. Aviso: Certifique -se de que você não está excluindo as chaves nas chaves de registro de nível superior (por exemplo, HKEY_CLASSES_ROOT , HKEY_CURRENT_USER etc.)