Estoy tratando de hacer un .exe con un archivo .py. Me leí el tutorial de http://www.py2exe.org/index.cgi/Tutorial y me funciono a la perfección. Mi problema es cuando en vez de hacer un código tan fácil como el del tutorial print "Hello world"
coloco funciones como por ejemplo:
def main():
a = 14
print a
if __name__ == '__main__':
main()
Instalarlo y crear el .exe lo hace pero cuando quiero ejecutarlo solo me abre y cierra rápido la ventana de la terminal.
proble agregando raw_input() y en el codigo escrito previamente corre bien. Ahora dejo mi codigo real que necesito correr para ver si me puede encontrar una solucion:
# 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()
Ademas agrego el codigo de mi setup.py:
from distutils.core import setup
import py2exe
setup(console=['Media_Yesterday_Top20.py'],
options={
'py2exe': {
'dll_excludes': ["ADVAPI32.dll",
"WLDAP32.dll"]
}
})