Python Forum
How can I make a python script create an EXE?
Thread Rating:
  • 0 Vote(s) - 0 Average
  • 1
  • 2
  • 3
  • 4
  • 5
How can I make a python script create an EXE?
#21
(Aug-23-2018, 07:34 AM)Axel_Erfurt Wrote: you forgot to import build ?
There is no need to import build,it's only needed from command line.

@ahmed_mokhles can show a run with Cx_Freeze as i used many times in the past.
Build a virtual environment with 3.6 as 3.7 is my main setup.
Virtual environment(build into 3.6 -->) can be great for troubleshooting,if there is a problem with build.
# Make enviroment
E:\div_code
λ py -3.6 -m venv cx_env

# Cd in
E:\div_code
λ cd cx_env

# Activate
E:\div_code\cx_env
λ E:\div_code\cx_env\Scripts\Activate

# Install cx_Freeze
(cx_env) E:\div_code\cx_env
λ pip install cx_Freeze
Collecting cx_Freeze
  Downloading https://files.pythonhosted.org/packages/3b/04/d68567b8f3265d3936e37c1ee8b3378dc189ec66b4d43650affbefcc69c5/cx_Freeze-5.1.1-cp36-cp36m-win32.whl (175kB)
    100% |████████████████████████████████| 184kB 853kB/s
Installing collected packages: cx-Freeze
Successfully installed cx-Freeze-5.1.1

# Install win32
(cx_env) E:\div_code\cx_env
λ pip install pypiwin32
Collecting pypiwin32
  Using cached https://files.pythonhosted.org/packages/d0/1b/2f292bbd742e369a100c91faa0483172cd91a1a422a6692055ac920946c5/pypiwin32-223-py3-none-any.whl
Collecting pywin32>=223 (from pypiwin32)
  Using cached https://files.pythonhosted.org/packages/d4/2d/b927e61c4a2b0aaaab72c8cb97cf748c319c399d804293164b0c43380d5f/pywin32-223-cp36-cp36m-win32.whl
Installing collected packages: pywin32, pypiwin32
Successfully installed pypiwin32-223 pywin32-223

(cx_env) E:\div_code\cx_env
λ ls
Include/  Lib/  Scripts/  coin_toss.py  cx_run.py  pip-selfcheck.json
At this point all is done from cx_env folder,so no path should be given.
# cx_run.py
from cx_Freeze import setup,Executable
import sys

# If need to include/exclude module/packages
includes = []
excludes = []
packages = []

# Console or Win32GUI
base = None
if sys.platform == "win32":
    base = 'Console'
    #base = 'Win32GUI'

# Name of file to make ".exe" of
filename = "coin_toss.py"
setup(
    name = 'Myapp',
    version = '0.1',
    description = 'Toss a coin',
    options = {'build_exe': {'excludes':excludes,'packages':packages,'includes':includes}},
    executables = [Executable(filename, base=base, icon = None)])

# --- From command line ---
#python cx_run.py build
The example code used before in post with Pyinstaller.
# coin_toss.py
import random
import time
 
class Coin:
    def __init__(self):
        self.sideup = "Heads"
 
    def toss(self):
        if random.randrange(2) == 0:
            self.sideup = "Heads"
        else:
            self.sideup = "Tails"
 
def toss_result():
    my_coin = Coin()
    print(f"This side is up: {my_coin.sideup}")
    print("I am tossing the coin...")
    time.sleep(4)
    my_coin.toss()
    print(f"This side is up: {my_coin.sideup}")
    input('Press Enter to exit')
 
if __name__ == "__main__":
    toss_result()
See that base = 'Console' because this is not a GUI code.

From command line build and test coin_toss.exe.
# Build exe
(cx_env) E:\div_code\cx_env
λ python cx_run.py build
running build
running build_exe
....

# Cd in
(cx_env) E:\div_code\cx_env
λ cd build\

(cx_env) E:\div_code\cx_env\build
λ cd exe.win32-3.6\

# exe placement
(cx_env) E:\div_code\cx_env\build\exe.win32-3.6
λ ls
coin_toss.exe*  lib/  python36.dll*

# Test it works
(cx_env) E:\div_code\cx_env\build\exe.win32-3.6
λ coin_toss.exe
This side is up: Heads
I am tossing the coin...
This side is up: Tails
Press Enter to exit

(cx_env) E:\div_code\cx_env\build\exe.win32-3.6
λ
Reply
#22
When I changed the base to console and tried again, the EXE gives the exact same error except now it shows in in the EXE console and not as a popup as it used to.

But you know what? I think this will never be solved until I REALLY tell you guys what I'm making.
I want to make a text encrypter, which when text is input, it encrypts it with the algorithm I made and creates another .py script that decrypts the text. But so no one can read the letter codes created I want the program to be in EXE form, but that will create a .py script which I also want in EXE form. So what I want to do is create an EXE out of the main program with pyinstaller, then I want that to create the decryption program and then compile it so that both are EXEs. Here is what I have till now:

PyEncrypt 2.0.py:
import os
import random
import time

logo = "\n ======================= PyEncrypt 2.0 ========================\n"

def initialize():
    os.system('title PyEncrypt 2.0')
    os.system('cls')
    os.system('color 0a')
    os.system('mode con: cols=64 lines=16')
    chars = str("abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ 1234567890-_',.:;+=()!@#$%^&*|/\\~`?><[]}{")
    global data
    data = {}

    for i in chars:
        data[i] = random.randint(1000000000, 10000000000)

def enterData():
    os.system('cls')
    print(logo)
    global filename
    filename = str(input("\n Enter a name for the output file:\n\n >>> "))
    os.system('cls')
    print(logo)
    global password
    password = str(input("\n Enter a password to protect your encrypted text:\n\n >>> "))
    os.system('cls')
    print(logo)
    textToEncrypt = str(input("\n Now enter the text you wish to encrypt:\n\n >>> "))
    OUTPUT = open(filename + ".txt", "w+")

    for i in range(len(textToEncrypt)):
        getValue = str(textToEncrypt[i])
        OUTPUT.write(str(data[getValue]) + "\n")

def createEncrypterProgram():
    DECRYPTER = open(filename + ".decrypt.py", "w+")
    DECRYPTER.write("""
import os
import time
os.system('title PyEncrypt 2.0 - Decrypt """ + '"' + filename + ".txt" + '"' + """')
os.system('cls')
os.system('color 0a')
os.system('mode con: cols=64 lines=16')
password = """ + '"' + password + '"' + """
filename = """ + '"' + filename + '"' + """
if os.path.isfile("./" + filename + ".txt"):
    os.system('cls')
else:
    os.system('cls')
    print(" ")
    print(" No file with encrypted text found!")
    time.sleep(0.5)
    exit()
os.system('cls')
print(" ")
print(" Enter the password that you used to encrypt your text:")
print(" ")
passwordCheck = str(input(" >>> "))
os.system('cls')
if password == passwordCheck:
    os.system('cls')
else:
    os.system('cls')
    print(" ")
    print(" Incorrect Password!")
    time.sleep(0.5)
    exit()
data = """ + str(data) + """
data2 = {val:key for (key, val) in data.items()}
INPUT = open(filename + ".txt", "r")
OUTPUT2 = open(filename + ".decrypted.txt", "w+")
for line in INPUT:
    OUTPUT2.write(str(data2[int(line)]))
os.system('cls')
print(" ")
print(" Decryption complete!")
time.sleep(0.5)
""")
    DECRYPTER.close()

def createCompiler():
    compiler = open("compiler.py", "w+")
    compiler.write("""
import sys
from cx_Freeze import setup, Executable

base = None
if sys.platform == "win32":
    base = "Console"

buildOptions = dict(
    packages = [ 'os', 'time'],
    excludes = [])

executables = [
    Executable(
        str(""" + '"' + "D:/Python/PyEncrypt 2.0/" + filename + '"' + """ + ".decrypt.py"),
        base = base,)]

setup(
    name='Decrypt',
    version = '2.0',
    description = 'Decrypt',
    options = dict(build_exe = buildOptions),
    executables = executables)
""")
    compiler.close()

initialize()
enterData()
createEncrypterProgram()
createCompiler()

os.system('python compiler.py build')
os.system('del compiler.py')

os.system('cls')
print(logo)
print("\n Encryption complete!")
time.sleep(0.5)
This encrypts, creates a decrypter and compiles it. However my problems are with the compiled EXE. Notice that this code creates a decrypter and then creates a compiler (the setup.py) and then runs it. The compiler should compile the decrypter. Plz help me with this and ask for any info you need. Note that this code only works on Windows!

Take the code, test it out on your PC and try to see what's wrong plz.
Thanks.
Reply
#23
this line

str(""" + '"' + "D:/Python/PyEncrypt 2.0/" + filename + '"' + """ + ".decrypt.py"),

looks wrong to me

it creates this string

Output:
+ '"' + "D:/Python/PyEncrypt 2.0/" + filename + '"' + .decrypt.py
that can not be a path, and you are using 2 files (filename and decrypt.py)


"D:/Python/PyEncrypt 2.0/" + filename

or

"'D:/Python/PyEncrypt 2.0/" + filename + "'"
Reply
#24
"filename" is only the name of the file without the extension so i'm pretty sure its not the issue
If you check it out you'll notice that the program asks for a filename.
Reply
#25
(Aug-26-2018, 03:57 PM)ahmed_mokhles Wrote: If you check it out you'll notice that the program asks for a filename.

yes, but there are too many quotes.

if i answer testapp yor code creates this path:
Output:
" + '"' + "D:/Python/PyEncrypt 2.0/" + filename + '"' + .decrypt.py
you can test it with

filename = "testapp"
print("""" + '"' + "D:/Python/PyEncrypt 2.0/" + filename + '"' + """ + ".decrypt.py")
is tht better?
filename = "testapp"
print("'D:/Python/PyEncrypt 2.0/" + filename + "' " +  "decrypt.py")
Output:
'D:/Python/PyEncrypt 2.0/testapp' decrypt.py
or do you want something like this

filename = "testapp"
print("'D:/Python/PyEncrypt 2.0/PyEncrypt 2.0.py' " + filename)
Output:
'D:/Python/PyEncrypt 2.0/PyEncrypt 2.0.py' testapp
Reply
#26
So many quotes because the program is actually creating another program. Plz read it carefully and look at all the quotes closely.
Reply
#27
Plus, the problem is not with my main program. Its only with the cx_Freeze setup.py.

Setup.py:
import sys
from cx_Freeze import setup, Executable

base = None
if sys.platform == "win32":
    base = "Console"

buildOptions = dict(
    packages = [],
    excludes = [])

executables = [
    Executable(
        str("filename.py"),
        base = base,)]

setup(
    name='filename',
    version = '1.0',
    description = 'filename',
    options = dict(build_exe = buildOptions),
    executables = executables)
When this compiles a .py program, the EXE does not work. So plz can you leave my main program and look at the code above? All I want is to know why this code doesn't work. BTW, as proof that the problem is not with my main program, I tried this setup.py on another python file and that EXE did not work too. So plz test the code above. Thanks.

PS: This has wasted so much of all our times, so I'd be glad to get it over with, and fast.
Reply


Possibly Related Threads…
Thread Author Replies Views Last Post
  Make entire script run again every 45 mo NDillard 0 293 Jan-23-2024, 09:40 PM
Last Post: NDillard
  Trying to make a board with turtle, nothing happens when running script Quascia 3 608 Nov-01-2023, 03:11 PM
Last Post: deanhystad
  Is there a *.bat DOS batch script to *.py Python Script converter? pstein 3 3,009 Jun-29-2023, 11:57 AM
Last Post: gologica
  Make console show after script was built with Pyinstaller --NOCONSOLE? H84Gabor 0 1,189 May-05-2022, 12:32 PM
Last Post: H84Gabor
  Make my py script work only on 1 compter tomtom 14 3,737 Feb-20-2022, 06:19 PM
Last Post: DPaul
  How to create a Kibana Visualisation with python script? adzadz 0 1,245 Jul-20-2020, 06:41 AM
Last Post: adzadz
  How to kill a bash script running as root from a python script? jc_lafleur 4 5,793 Jun-26-2020, 10:50 PM
Last Post: jc_lafleur
  How to make this function general to create binary numbers? (many nested for loops) dospina 4 4,332 Jun-24-2020, 04:05 AM
Last Post: deanhystad
  Make the script read from any directory falahfakhri 2 2,113 Jun-15-2020, 02:18 PM
Last Post: falahfakhri
  crontab on RHEL7 not calling python script wrapped in shell script benthomson 1 2,254 May-28-2020, 05:27 PM
Last Post: micseydel

Forum Jump:

User Panel Messages

Announcements
Announcement #1 8/1/2020
Announcement #2 8/2/2020
Announcement #3 8/6/2020