Program enters an infinite loop after being packaged into a single exe file using pyinstaller

I am encountering an issue where my program enters an infinite loop after I package it into a single exe file using pyinstaller. The program runs fine when executed directly from the source code. Here are the detailed steps and parts of my script:

  1. Setting up MSRA (Microsoft Remote Assistance) by modifying the registry.
  2. Configuring the firewall to allow MSRA applications.
  3. Generating an invitation file and starting a listener.
  4. Sending the invitation file via email.

Due to the MSRA listener blocking the current process in step 3, I used the multiprocessing module to handle it. To prevent the listener process from terminating when the script finishes, I added an input() method at the end of the script. Everything works as expected when running the script directly.

However, when I use pyinstaller -F msra.py to generate a single exe file and run it as an administrator, the script enters an infinite loop, repeatedly printing outputs as if it’s restarting over and over again.

Has anyone encountered a similar problem or can provide guidance on how to fix this? Any help would be greatly appreciated.

output screenshot

I found that pyinstaller can cause an infinite loop when using multiprocessing, so I added multiprocessing.freeze_support() before the multiprocessing code, but it didn’t resolve the issue.

Here is my complete code:

import multiprocessing
from pathlib import Path
import random
import string
import subprocess
import time
import win32com.client
import winreg

def enable_remote_assistance():
    try:
        # Open the registry key
        key = winreg.OpenKey(winreg.HKEY_LOCAL_MACHINE, r"SYSTEMCurrentControlSetControlRemote Assistance", 0, winreg.KEY_SET_VALUE)
        # Set the value of fAllowToGetHelp to 1
        winreg.SetValueEx(key, "fAllowToGetHelp", 0, winreg.REG_DWORD, 1)
        winreg.CloseKey(key)
        print("Remote Assistance has been enabled in the registry.")
    except Exception as e:
        print(f"Error enabling Remote Assistance in the registry: {e}")

def allow_remote_assistance_in_firewall():
    try:
        # Allow Remote Assistance application in the firewall
        subprocess.run('netsh advfirewall firewall set rule group="remote assistance" new enable=Yes', shell=True, check=True)
        print("Remote Assistance has been allowed in Firewall.")
    except subprocess.CalledProcessError as e:
        print(f"Error allowing Remote Assistance in Firewall: {e}")

def create_remote_assistance_invitation(file_path, password):
    try:
        # Build the command
        command = f'msra /saveasfile "{file_path}" "{password}"'
        
        # Execute the command using subprocess module
        result = subprocess.Popen(command, shell=True)
        
        if result.returncode == 0:
            print(f"Invitation file created at: {file_path}")
        else:
            print(f"Failed to create invitation file, return code: {result.returncode}")
    except subprocess.CalledProcessError as e:
        print(f"Error creating invitation file: {e}")

def send_email_with_attachment(attachment_path):
    retries = 5
    while retries > 0:
        if attachment_path.exists():
            break
        print(f"Invitation file not found. Waiting for {attachment_path} to be created...")
        time.sleep(1)
        retries -= 1
    else:
        raise FileNotFoundError(f"Invitation file {attachment_path} not found after waiting.")

    outlook = win32com.client.Dispatch("Outlook.Application")
    subject = "Remote Assistance Invitation"
    body = f"Please find the Remote Assistance invitation attached.nThe password to open the invitation is: {password}"
    to = "[email protected]"
    
    try:
        mail = outlook.CreateItem(0)  # 0 represents a mail item

        mail.Subject = subject
        mail.Body = body
        mail.To = to

        mail.Attachments.Add(str(attachment_path))

        mail.Send()
        print(f"Email sent to {to} with attachment {attachment_path}")
    except Exception as e:
        print(f"Error sending email: {e}")

def generate_password(length=12):
    """Generate a random password containing only uppercase letters and digits"""
    characters = string.ascii_uppercase + string.digits
    password = ''.join(random.choice(characters) for i in range(length))
    return password

if __name__ == "__main__":
    # Set the invitation file save path to the directory where the script is located and generate the password
    script_dir = Path(__file__).parent
    invitation_file_path = script_dir / "RAInvitation.msrcincident"
    print(invitation_file_path)
    password = generate_password()
    
    # Enable Remote Assistance
    enable_remote_assistance()
    
    # Allow Remote Assistance application in the firewall
    allow_remote_assistance_in_firewall()
    
    # Check if there is an existing assistance file at the target location, if so, delete it to prevent the main thread from sending the old assistance file too quickly
    if invitation_file_path.exists():
        invitation_file_path.unlink()
        print(f"Existing file at {invitation_file_path} has been removed.")
    
    # Create a process to generate the invitation file
    multiprocessing.freeze_support()
    process = multiprocessing.Process(target=create_remote_assistance_invitation, args=(invitation_file_path, password))
    process.start()
    
    # Send the email
    send_email_with_attachment(invitation_file_path)
    input()

Trang chủ Giới thiệu Sinh nhật bé trai Sinh nhật bé gái Tổ chức sự kiện Biểu diễn giải trí Dịch vụ khác Trang trí tiệc cưới Tổ chức khai trương Tư vấn dịch vụ Thư viện ảnh Tin tức - sự kiện Liên hệ Chú hề sinh nhật Trang trí YEAR END PARTY công ty Trang trí tất niên cuối năm Trang trí tất niên xu hướng mới nhất Trang trí sinh nhật bé trai Hải Đăng Trang trí sinh nhật bé Khánh Vân Trang trí sinh nhật Bích Ngân Trang trí sinh nhật bé Thanh Trang Thuê ông già Noel phát quà Biểu diễn xiếc khỉ Xiếc quay đĩa Dịch vụ tổ chức sự kiện 5 sao Thông tin về chúng tôi Dịch vụ sinh nhật bé trai Dịch vụ sinh nhật bé gái Sự kiện trọn gói Các tiết mục giải trí Dịch vụ bổ trợ Tiệc cưới sang trọng Dịch vụ khai trương Tư vấn tổ chức sự kiện Hình ảnh sự kiện Cập nhật tin tức Liên hệ ngay Thuê chú hề chuyên nghiệp Tiệc tất niên cho công ty Trang trí tiệc cuối năm Tiệc tất niên độc đáo Sinh nhật bé Hải Đăng Sinh nhật đáng yêu bé Khánh Vân Sinh nhật sang trọng Bích Ngân Tiệc sinh nhật bé Thanh Trang Dịch vụ ông già Noel Xiếc thú vui nhộn Biểu diễn xiếc quay đĩa Dịch vụ tổ chức tiệc uy tín Khám phá dịch vụ của chúng tôi Tiệc sinh nhật cho bé trai Trang trí tiệc cho bé gái Gói sự kiện chuyên nghiệp Chương trình giải trí hấp dẫn Dịch vụ hỗ trợ sự kiện Trang trí tiệc cưới đẹp Khởi đầu thành công với khai trương Chuyên gia tư vấn sự kiện Xem ảnh các sự kiện đẹp Tin mới về sự kiện Kết nối với đội ngũ chuyên gia Chú hề vui nhộn cho tiệc sinh nhật Ý tưởng tiệc cuối năm Tất niên độc đáo Trang trí tiệc hiện đại Tổ chức sinh nhật cho Hải Đăng Sinh nhật độc quyền Khánh Vân Phong cách tiệc Bích Ngân Trang trí tiệc bé Thanh Trang Thuê dịch vụ ông già Noel chuyên nghiệp Xem xiếc khỉ đặc sắc Xiếc quay đĩa thú vị
Trang chủ Giới thiệu Sinh nhật bé trai Sinh nhật bé gái Tổ chức sự kiện Biểu diễn giải trí Dịch vụ khác Trang trí tiệc cưới Tổ chức khai trương Tư vấn dịch vụ Thư viện ảnh Tin tức - sự kiện Liên hệ Chú hề sinh nhật Trang trí YEAR END PARTY công ty Trang trí tất niên cuối năm Trang trí tất niên xu hướng mới nhất Trang trí sinh nhật bé trai Hải Đăng Trang trí sinh nhật bé Khánh Vân Trang trí sinh nhật Bích Ngân Trang trí sinh nhật bé Thanh Trang Thuê ông già Noel phát quà Biểu diễn xiếc khỉ Xiếc quay đĩa
Thiết kế website Thiết kế website Thiết kế website Cách kháng tài khoản quảng cáo Mua bán Fanpage Facebook Dịch vụ SEO Tổ chức sinh nhật