PyInstaller exe文件不会创建日志文件

时间:2017-05-04 13:37:19

标签: python python-2.7 pyinstaller

我正在尝试使我的脚本可执行,因此我可以将其发送给我的同事。我正在使用PyInstaller

pyinstaller --onefile main.py

创建两个文件夹。当我打开dist / main.exe时,出了点问题,但我不知道是什么,因为它没有创建日志文件。我无法弄清楚为什么。当我运行main.py时,会立即创建日志文件。

你能看看吗?

# 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()

1 个答案:

答案 0 :(得分:0)

当您冻结应用程序时,文件可能位于 sys._MEIPASS

这是我在我的应用程序中测试的一个小例子:

 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