2

I wrote a simple script in Python 3.9.5 and converted it to .exe by running

pyinstaller --onefile -w myscript.py

My script works perfectly fine when I launched it from the python file, but it doesn't work. When I clicked on the .exe file located in the dist folder. It says Failed to execute script myscript

I tried creating a much simpler script with only print("Hello World!") and converted it to .exe with the exact same steps - It works perfectly fine... I have no idea why my first script did not work.

Here's the code I created:

import pyautogui
from pynput import keyboard
import time
import threading

text = pyautogui.prompt('Text: ')
interval = pyautogui.prompt('Interval: ')


def spam():
    while running:
        pyautogui.press('enter')
        pyautogui.write(text)
        pyautogui.press('enter')
        time.sleep(float(interval))


running = False


def on_press(key):
    global running
    if key == keyboard.Key.f1:
        running = running ^ True
        if running:
            t = threading.Thread(target=spam)
            t.start()


with keyboard.Listener(on_press=on_press) as listener:
    listener.join()

It is basically a simple spam bot (for educational purpose) enter image description here

gfdsweds
  • 345
  • 3
  • 11

2 Answers2

0

Edit: Skip step 1 if you don't have 3rd party antivirus. Rest of the steps are still applicable for all cases.


Step 1) Turn off your 3rd party antivirus

Step 2) Turn off windows defender which automatically turns on after 3rd party antivirus deactivation. Type the below code in powershell. Ensure admin powershell and not unprivilleged powershell.

Set-MpPreference -DisableRealtimeMonitoring $true

Step 3) Run your exe file

Joshua
  • 551
  • 4
  • 13
  • this doesn't explain why this is required, nor issues with doing this, but it seems logically sound that the process could fail due to OS safety settings – ti7 Jun 22 '21 at 15:54
  • Nope, doesn't work...Btw, I made another script and it worked fine. The only difference is that 1 has modules and 1 doesn't... – Cassiterite Jun 22 '21 at 17:24
0

You can do:

pyinstaller -w --onefile script.py --hidden-import pynput.keyboard._win32 --hidden-import pynput.mouse._win32

See here.

The reason is because pynput uses importlib to import packages, but PyInstaller could not detect it.

You can also read the When Things Go Wrong section about hidden imports.

gfdsweds
  • 345
  • 3
  • 11