D
D
Diolorca2022-01-21 06:45:48
Windows
Diolorca, 2022-01-21 06:45:48

How to pass file path to python script via windows context menu?

There is a small file converter script that is called through the windows context menu.
The script was added to the context menu using a registry tweak:

Windows Registry Editor Version 5.00

[HKEY_CLASSES_ROOT\*\shell\python]
@="pdf2img" 

[HKEY_CLASSES_ROOT\*\shell\python\command]
@="cmd /k python c:\\Scripts\\pdf2jpg.py \"%1\""

[HKEY_CLASSES_ROOT\AllFilesystemObjects\shell\python]
@="pdf2img" 

[HKEY_CLASSES_ROOT\AllFilesystemObjects\shell\python\command]
@="cmd /k python c:\\Scripts\\pdf2jpg.py \"%1\""

Сам скрипт принимает путь до файла с помощью argv[1].

The problem is that if I select multiple files and run the script through the context menu, then as many instances of the script are launched as there are files I have selected. How can I make one instance of the script run and pass paths to all selected files there?

Answer the question

In order to leave comments, you need to log in

2 answer(s)
V
Vindicar, 2022-01-21
@Diolorca

No, the problem is not in python, the problem is in Windows.
The stackoverflow suggested a solution - move your program to the "Send To" item, where the required behavior is better supported.
If this is not enough, you will have to write a plugin for windows explorer.

A
Alexander, 2022-01-21
@shabelski89

I also think that the snag is in Windows, but the question is how to get around it with a python?
maybe through a singleton?
what happens with this code?

from pdf2image import convert_from_path
import os
from sys import argv


class SingletonMeta(type):
    """
    Класс Одиночка, для запуска единственного экземпляра
    """

    _instances = {}

    def __call__(cls, *args, **kwargs):
        if cls not in cls._instances:
            instance = super().__call__(*args, **kwargs)
            cls._instances[cls] = instance
        return cls._instances[cls]


class Converter(metaclass=SingletonMeta):
    CONST = 200
    POPPLER_PATH = r'C:\Program Files\poppler-0.68.0\bin'

    def convert_file(self):
        """
        Метод для конвертации файла pdf в картинки постранично
        """

        print("-" * 50)
        print('Конвертирование файла ', argv[1])
        print("-" * 50)

        filepath = argv[1]
        path = os.path.dirname(filepath)
        full_filename = os.path.basename(path)
        filename_without_extension = os.path.splitext(full_filename)[0]

        # конвертация и сохранние файлов
        pages = convert_from_path(path, self.CONST, poppler_path=self.POPPLER_PATH)
        if not os.path.isdir(filename_without_extension):
            print("-" * 50)
            print("Конвертирование завершено!")
            print("-" * 50)
            print(f"Создание папки {filename_without_extension} под файлы картинок")
            try:
                os.mkdir(filename_without_extension)
            except OSError as E:
                print(E)
        print("-" * 50)

        for i, page in enumerate(pages):
            print(f"Сохранение страницы {i + 1} как картинки")
            converted_filename = f"{full_filename}_{i + 1}.jpg"
            page.save(os.path.join(path, full_filename, converted_filename), 'JPEG')
        print("-" * 50)
        print('Сохранение завершено!')
        print("-" * 50)


if __name__ == "__main__":
    s = Converter()
    s.convert_file()

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question