[Python] Python Debugging Behavior Different From C# Implementation of Python

Discussão em 'Python' iniciado por Stack, Agosto 15, 2025.

  1. Stack

    Stack Membro Participativo

    I have a script that is just trying to check if an Excel file is encrypted with a password. The purpose is that I am building a GUI that will toggle a password UI element to the user (sometimes the file that will be inputted is not encrypted).

    My problem is that when I am debugging in VS Code, the code behaves as expected. But then I tried packaging into an exe using pyinstaller and call it in C#, the behavior changes to an DecryptionError instead of InvalidKeyError. This current iteration then used my venv while calling the python file directly. Same result, unfortunately.

    Initially, I was trying to get this feature to work within C#, but was unable, so I went through this Python approach. If there are better solutions, I am open for it :)

    Here's my quick Python script:

    import io
    import msoffcrypto
    import argparse

    from msoffcrypto.exceptions import InvalidKeyError, DecryptionError

    if __name__ == '__main__':
    parser= parser = argparse.ArgumentParser()

    parser.add_argument('--filepath', required=True, help='Path to the encrypted Office file')
    parser.add_argument('--test_string', required=True, help='Password to test against the encrypted file')

    args = parser.parse_args()
    file_path = args.filepath
    test_pass = args.test_string

    print(f'Checking file: {file_path} with password: {test_pass}')

    try:
    # Attempt to open the file and decrypt it with the pseudo password
    with open(file_path, 'rb') as f:
    office_file = msoffcrypto_OfficeFile(f)
    office_file.load_key(password=test_pass)
    decrypted = io.BytesIO()
    office_file.decrypt(decrypted)

    # Case where there is password encryption
    except InvalidKeyError:
    print(True)

    # Case where there is NOT password encryption
    except DecryptionError as e:
    print(False)

    # Edge case
    except Exception as e:
    print(False)


    Here's my C# implementation:

    private static bool IsExcelFilePasswordProtected(string filePath)
    {
    string venvPython = Path.Combine(AppContext.BaseDirectory, "venv", "Scripts", "python.exe"); // Windows
    string scriptPath = Path.Combine(AppContext.BaseDirectory, "CheckPass.py");
    string args = $"\"{scriptPath}\" --filepath \"{filePath}\" --test_string notapassword";

    var psi = new ProcessStartInfo
    {
    FileName = venvPython,
    Arguments = args,
    RedirectStandardOutput = true,
    UseShellExecute = false,
    CreateNoWindow = true
    };

    try
    {
    using (var process = Process.Start(psi))
    {
    string output = process?.StandardOutput.ReadToEnd() ?? string.Empty;
    process?.WaitForExit();
    bool hasPassword = bool.TryParse(output.Trim(), out bool result) && result;
    return hasPassword;
    }
    }
    catch (Exception e)
    {
    return false;
    }
    }

    Continue reading...

Compartilhe esta Página