.py a .exe Python

1

I'm trying to make an .exe with a .py file. I read the tutorial link and it worked perfectly. My problem is when instead of making a code as easy as the tutorial print "Hello world" I place functions such as:

def main():
    a = 14
    print a

if __name__ == '__main__':
    main() 

Install it and create the .exe it does but when I want to run it just opens and closes the terminal window quickly.

proble adding raw_input () and in the previously written code it runs fine. Now I leave my real code that I need to run to see if you can find me a solution:

# coding=utf-8
from urllib import urlencode
import pycurl
import pprint
import json
from io import BytesIO
import ast
import requests
import csv
import os
import pandas as pd 
from datetime import date, timedelta
import zipfile


def main():
    url_login('https://partners.streamrail.com/api/v2/login')
    login('marti', '44444')
    report('https://partners.streamrail.com/data-export/data/custom/5a2ff9a88783470002ad62bd', 'Top20_Media_Yesterday.zip')
    zip('Top20_Media_Yesterday.zip')
    Top20("Top20_Media_Yesterday.zip","Top20_Media_Yesterday.csv")
    Orden_imp()
    name_csv_top20('Top20_Media_Yesterday.csv')
    remove_files("Top20_Media_Yesterday.csv","Top20_Media_Yesterday.zip")


def url_login(url): #Llamado a la url del login
    global data
    data = BytesIO()
    global c
    c = pycurl.Curl()
    c.setopt(c.URL, url)


def login(user,passwd): #Usuario y contraseña, almacenamiento de token tambien
    post_data = {'username': user, 'password': passwd}
    postfields = urlencode(post_data)
    c.setopt(c.POSTFIELDS, postfields)
    c.setopt(c.WRITEFUNCTION, data.write) #Eliminar esta y las del dicc para volver al codigo original
    c.perform()
    dictionary = json.loads(data.getvalue())
    global d
    d = dictionary["access_token"]


def report(url_report, name_file): #Url del reporte + almacenamiento del reporte en zip
    url = url_report 
    headers = {
        'content-type': "application/json",
        'cache-control': "no-cache",
        'Authorization': 'Bearer {}'.format(d)
        }
    data = name_file #Nombre del reporte
    response = requests.request("GET", url, headers=headers) #almacena reporte en la variable
    with open(data, 'wb') as f: #Save report
            for chunk in response.iter_content():
                f.write(chunk)
    print response.status_code,("(status_code)"),("- Reporte descargado:"), response.status_code == requests.codes.ok


def zip(name_zip): #Extraccion del zip
    zip_ref = zipfile.ZipFile(name_zip, 'r')
    zip_ref.extractall()
    zip_ref.close()

def Top20(name_zip, output_file): #Modificacion CSV zip a csv con el top 20 de la media
    #Creacion y lectura de CSV's
    with zipfile.ZipFile(name_zip) as z:
        lista = z.namelist()
        global filename
        filename = ''.join(lista)
    with open(filename) as csvfile, open(output_file,  "w") as output:
        reader = csv.DictReader(csvfile)
        cols = ("domain","ddomain","opportunities", "impressions", "fillRate", "DATA")
        writer = csv.DictWriter(output, fieldnames=cols, extrasaction='ignore')
        writer.writeheader()
        #Operaciones para llegar al top 20 Media
        for row in reader:
            row['fillRate'] = '{:.2f}'.format(float(row['fillRate']) * 100)
            if row['ddomain']  == "":
                if row['domain']  == "":
                    row['ddomain'] = "App"
                    row['domain'] = " "
            if row['domain'] == row['ddomain']:
                row['domain'] = "Real Site"    
            if row['domain']  == "":
                row['domain'] = "Detected Only"
            if row['ddomain']  == "":
                row['ddomain'] = "Vast Media"
            if row['ddomain'] != row['domain']:
                if row['ddomain'] != "Vast Media":
                    if row['domain'] != "Real Site":
                        if row['domain'] != "Detected Only":
                            if row['ddomain'] != "App":
                                row['DATA'] = "FAKE"
                            else:
                                row['DATA'] = "OK"
                        else:
                            row['DATA'] = "OK"
                    else:
                        row['DATA'] = "OK"
                else:
                    row['DATA'] = "OK"
            writer.writerow(row)


def Orden_imp():
#Orden y de mayor a menor en impresiones
    movies = pd.read_csv('Top20_Media_Yesterday.csv')
    movies = movies.sort_values(['impressions'], ascending=False) #Orden de mayor a menor impresiones
    movies = movies.to_csv("Top20_Media_Yesterday.csv")
    movies = pd.read_csv('Top20_Media_Yesterday.csv', nrows=20) #Top 20 media yesteday
    movies = movies.to_csv("Top20_Media_Yesterday.csv")


def name_csv_top20(name): #Nombre file fecha yesterday + creacion CSV

    yesterday = date.today() - timedelta(1)
    fecha = yesterday.strftime("%d-%m-%y")
    base ='Top20_Media_{}.csv'.format(fecha)
    with open(name, 'r') as csvfile, open(base,  "w") as output:
        reader = csv.DictReader(csvfile)
        cols = ("domain","ddomain","opportunities", "impressions", "fillRate", "DATA")
        writer = csv.DictWriter(output, fieldnames=cols, extrasaction='ignore')
        writer.writeheader()
        for row in reader:
            writer.writerow(row)

    #Cambio de nombre celda (domain to Category)
    r = csv.reader(open(base)) 
    lines = [l for l in r]
    lines[0][0] = 'Category'
    writer = csv.writer(open(base, 'w'))
    writer.writerows(lines)


def remove_files(topcsv,zipf):
    #Borrado de archivos innecesarios
    os.remove(topcsv)
    os.remove(filename)
    os.remove(zipf)

    print("YOUR TOP 20 MEDIA IS DONE")


if __name__ == '__main__':
    main()

raw_input()

I also add the code of my setup.py:

from distutils.core import setup
import py2exe



setup(console=['Media_Yesterday_Top20.py'],
      options={
                'py2exe': { 
                'dll_excludes': ["ADVAPI32.dll",
                                 "WLDAP32.dll"]

              }

                })
    
asked by Martin Bouhier 13.12.2017 в 05:54
source

2 answers

1

In windows you can use the mcvcrt module. At the beginning of your program you import it: import msvcrt And then at the end of your program you put: msvcrt.getch () This is enough for the program to wait for a keystroke to exit.

There is also another variant using the function to read from the keyboard. As the last line of your program, you put: raw_input ()

And the cmd will remain open until you close it or press a key, this last method is valid for any operating system while the first method is only valid in windows.

    
answered by 13.12.2017 в 06:08
1

pyinstaller is better option to compile a windows .exe.

link

pip install pyinstaller

pyinstaller yourprogram.py

    
answered by 14.12.2017 в 20:21