2

I'm trying to make my scripts executable so I can send it to my colleague. I'm using PyInstaller.

pyinstaller --onefile main.py

Which creates two folders. When I open dist/main.exe, something is wrong but I don't know what because it doesn't create a log file. I can't figure out why. When I run main.py, the log file is created immediately.

Could you check it out?

# coding=utf-8
from __future__ import print_function
import csv
import os
import time
import logging
import sys
import traceback
from spider import is_connected
from database import Database
filename = os.path.join(os.path.dirname(os.path.realpath(__file__)), 'log.log')
logging.basicConfig(filename=filename, level=logging.INFO, filemode='w')

logger = logging.getLogger(__name__)
def printProgressBar(iteration, total, prefix='', suffix='', decimals=1, length=100, fill=u'█'):
    """
    Call in a loop to create terminal progress bar
    @params:
        iteration   - Required  : current iteration (Int)
        total       - Required  : total iterations (Int)
        prefix      - Optional  : prefix string (Str)
        suffix      - Optional  : suffix string (Str)
        decimals    - Optional  : positive number of decimals in percent complete (Int)
        length      - Optional  : character length of bar (Int)
        fill        - Optional  : bar fill character (Str)
    """
    percent = ("{0:." + str(decimals) + "f}").format(100 * (iteration / float(total)))
    filledLength = int(length * iteration // total)
    bar = fill * filledLength + '-' * (length - filledLength)
    print('\r%s |%s| %s%% %s' % (prefix, bar, percent, suffix))
    # Print New Line on Complete
    if iteration == total:
        print()


if __name__ == '__main__':
    print(os.path.join(os.path.dirname(os.path.realpath(__file__)), 'log.log'))
    logger.info('Download started...')
    connected = is_connected()
    logger.info('Checking connection... {}'.format(connected))
    if not connected:
        logger.info('Program closed - no connection...')
        sys.exit()
    db = Database()
    if not os.path.isdir("output"):
        print('Nenasla sa zlozka "output"...')
        logger.info('No output folder')
        input()
        sys.exit()
    if not os.path.isdir("csv"):
        print('Nenasla sa zlozka "csv"...')
        logger.info('No csv folder')
        input()
        sys.exit()

    print('Spracovavanie suboru "input.csv"...')
    filename = 'output_{}.csv'.format(time.strftime("%Y%m%d-%H%M%S"))
    try:
        with open('csv/input.csv') as f:
            with open('output/'+filename, 'wb') as o:
                reader = csv.DictReader(f)
                reader.fieldnames.append('VAT added')
                writer = csv.DictWriter(o, fieldnames=reader.fieldnames)
                writer.writeheader()
                r_list = list(reader)
                rows = len(r_list)
                for n, line in enumerate(r_list):
                    if n>0:
                        printProgressBar(n,rows)
                        code = line['Lot number'].strip()
                        vat = db.get_or_set_vat(code)
                        logger.info('outer vat')
                        logger.info(vat)
                        logger.info('YES' if vat else 'NO' if vat == False else 'UNKNOWN')
                        line['VAT added'] = 'YES' if vat else 'NO' if vat == False else 'UNKNOWN'
                        writer.writerow(line)
    except IOError as e:
        print(e)
        logger.info('IOError')
        logger.info(traceback.format_exc())
        print('Chyba: zrejme nenaslo subor "input.csv" - skontrolujte nazov suboru v zlozke csv')
        input()
        sys.exit()
    print()
    print('Koniec stahovania - {}'.format(filename))
    input()
Milano
  • 18,048
  • 37
  • 153
  • 353
  • Do you get any errors? Pls, check permissions in folder where you want to put the file. – Eugene Lisitsky May 04 '17 at 13:46
  • @EugeneLisitsky The only thing I detected is Warning: WARNING: file already exists but should not: C:\Users\Milano\AppData\Local\Temp\_MEI95682\include\pyconfig.h – Milano May 04 '17 at 13:50
  • @EugeneLisitsky I'm on Windows and I'm admin. I opened the main.exe using administrator and still the same problem. – Milano May 04 '17 at 13:51
  • The pyinstaller onefile is actually unzipping the python scripts in a temporary folder (you see that in your error), which is also the current folder for your script. Your file should be generated in there. To fix that, try the logic of [this approach](http://stackoverflow.com/a/36456550/3837382). – Repiklis May 04 '17 at 14:07
  • What does it print? – Eugene Lisitsky May 04 '17 at 15:08

2 Answers2

0

As you froze the application the File may be located under sys._MEIPASS

Here is a little example I tested in my application:

 if hasattr(sys, "_MEIPASS"):
            base_dir = os.path.join(sys._MEIPASS)
            print(base_dir)
            print(sys.argv[0])
>> C:\Users\Hendr\AppData\Local\Temp\_MEI986122
>> C:\Users\Hendr\Documents\coding_stuff\dist\test.exe
0x45
  • 779
  • 3
  • 7
  • 26
0

I have the same problem. The following scheme is feasible.

if hasattr(sys, "_MEIPASS"):                   
  print("base dir = ", sys._MEIPASS)
  CURRENTDIR = os.path.dirname(os.path.abspath(sys.argv[0]))
else:
  CURRENTDIR = os.path.dirname(os.path.abspath(__file__))

print('cur dir = ', CURRENTDIR)
4b0
  • 21,981
  • 30
  • 95
  • 142