我正在Windows 10 OS上使用Pycharm 2018.2.4和Python 3.6.2。 我刚刚用Python编写了我的第一个应用程序。 该应用程序: -网上废金属市场和欧元/美元信息。 -将信息发送到csv文件和Excel文件中(以便学习:) -下一步将是绘制数据并在投资组合价值达到一定金额时发送电子邮件
使用pycharm启动程序时,该方法有效。
我试图将.py转换为.exe文件 我使用pyinstaller 尽管有一个while循环,该程序仍会直接打开和关闭,最后输入命令。
阅读后,我尝试一些解决方案,包括: -输入() -pyinstaller -c -F -i cm_icon.ico console_monopoly.py -cxfreeze
但结果始终相同! 有人知道如何保持程序正常运行吗?有一会儿我虽然程序打开和关闭但是可以工作。但是CSV文件未更新!该程序在后台运行可能会很有趣。
在我的代码后面(请注意,值仅是示例):
#scrap website Application
#================================================
#import useful library
#import BRequests from eautifulSoup to catch data from web
from bs4 import BeautifulSoup
import requests
#import time to get time functions
import time
#import keyboard hook and simulate function
import keyboard
#import date to get date funcction
from datetime import date
#import datetime function (not sure that is usefull considering we already import date and time ? to be checked
import datetime
#import csv function to then send data into a csv file
import csv
#import all libraries to send data into excel spreadsheet
import openpyxl
from openpyxl import workbook
from openpyxl import load_workbook
#import libraries to plot data
#test if Nasdacq is open 15h30 22h00 french hour.
#start Core Program
#adding a try before while to get keyboardinterrupt function working
try:
# start a while loop to ensure checking data every XX seconds
while True:
#today variable creation to record day information
today = date.today()
print(today)
#now variable creation to record hour minute second
now = datetime.datetime.now()
print(now.hour, now.minute, now.second)
#which webpage we're working on
source = requests.get('https://www.boursorama.com/cours/AMZN/').text
#lxml is the most feature-rich and easy-to-use library for processing XML and HTML in the Python language
soup = BeautifulSoup(source,'lxml')
#I look for <div>syntax which contain text 'c-faceplate__price'=>information found when with chrome I inspect the website
#I use for...in due to the fact that in the website there are many div<>
for cotation in soup.find_all('div','c-faceplate__price'):
#transform cotation in string in order to split then information
cotationa=str(cotation)
#1st split finding [2] the third item of the split
cotationab=cotationa.split('>')[2]
#2nd split finding [0] the first item of the split
cotationac=cotationab.split('<')[0]
# print(cotationac)
#remove space from text to then convert into float for calculation
cotationad = cotationac.replace(" ","")
#print(cotationad)
#convert string into float with only 4 decimals
cotationae=round(float(cotationad),4)
print('Price of Amazon share is ' + str(cotationae)+ ' Dollars')
#=============================================================================================================
#restart with new webpage with to catch Euro/Dollar quotation
#which webpage we're working on
source = requests.get('https://www.zonebourse.com/EURO-US-DOLLAR-EUR-USD-4591/').text
#lxml is the most feature-rich and easy-to-use library for processing XML and HTML in the Python language
soup = BeautifulSoup(source,'lxml')
#I look for <table>syntax which contain text 'td'=>information found when with chrome I inspect the website
#I use for...in due to the fact that in the website there are many table<>
for mon in soup.find_all('td', 'fvPrice colorBlack'):
print(mon)
# transform mon in string in order to split then information
mona = str(mon)
#1st split finding [1] the second item of the split
monab=mona.split('>')[1]
#print(monab)
#2nd split finding [0] the first item of the split
monac=monab.split('<')[0]
#print(monac)
#remove space from text to then convert into float for calculation
monad = monac.replace(" ","")
#print(monad)
#convert string into float
monae=round(float(monad),4)
print('The Euro/Dollar parity is ' + str(monae)+ ' dollars for 1 euro')
#==============================================================================================================
#creation some variables for calculation
#nb of share in portfolio
nbact=15
#what is the purchasing value of the portfolio => use in France due to the fact we pay tax on the difference between sales price and purchase price
valacht = 900
#total value of portfolio in dollars
totactdol=round((nbact*cotationae),4)
print('The portfolio total value is ' + str(totactdol) + ' Dollars')
#total value of portfolio in euro
totacteur=round((totactdol/monae),4)
print('The portfolio total value is ' + str(totacteur) + ' Euro')
#calculation of the brokerage fees => 0.75% in this case
frscourt=0.0075
totcourt = round((totacteur*frscourt),4)
print('The amount of the brokerage fees is ' + str(totcourt) + ' Euro')
#Value of the portfolio after brokerage fess
portcourt=round((totacteur-totcourt),4)
print('The value of the portfolio after brokerage fees is ' + str(portcourt) + ' Euro')
#calculation of the base of taxes=> difference between sell price - purchase price
valimp=round((totacteur-valacht),4)
print('Taxes will be paid onthe amount of ' + str(valimp) + ' Euro')
#Taxes rate => 30% in this case (French flat tax
tximp=0.3
#Amount of the tax to be paid
monimp=round((tximp*valimp),4)
print('The amount of tax to be paid is ' + str(monimp) + ' Euro')
#Available cash after brokerage fees and payment of the tax
cashdisp=round((portcourt-monimp),4)
print('The available cash is ' + str(cashdisp) + ' Euro')
#======================================================================================================
#registering information in CSV
#open CSV file called AmznPriceRecord in add mode and called apr
#note that the csv file (for the moment), must be in same folder than the project
#FOR THE FIRST RUN with open('AmznPriceRecord.csv','w') as apr: TO WRITE ALL COLUMN
#FOR SECOND RUN with open('AmznPriceRecord.csv','a') as apr: TO ADD LINES
#YOU CAN DIRECTLY WORK IN ADD IF YOU PREPARED CSV FILE BEFORE
#one day could had a function which test if file existing or not
with open('AmznPriceRecord.csv','a') as apr:
#we add column name
fields = ['Date','Heure','AMZN Price $','$/€','Total Portfolio $','Total Portfolio €','Brokerage Fess','Portfolio after fees','Tax Basis','Tax to be paid','Free Cash']
#we use a CSV dictwriter to write in this file
writer = csv.DictWriter(apr, fieldnames=fields)
#not understanding why exactly
# writer.writeheader()
#which information we add at wich column
writer.writerow({'Date':today,'Heure':now.strftime("%H : %M :%S"),'AMZN Price $':cotationae,'$/€':monae,'Total Portfolio $':totactdol,'Total Portfolio €':totacteur,'Brokerage Fess':totcourt,'Portfolio after fees':portcourt,'Tax Basis':valimp,'Tax to be paid':monimp,'Free Cash':cashdisp})
#====================================================
#registering informations in Excel
#workbook name
# import load_workbook
# set file path
filepath = "/Users/domin/OneDrive/Documents/Programmation/Code python/Projets Python/AmznShareScrap/AmznShareScrap/venv/Scripts/AMZNPriceExcel.xlsx"
# load AMZNPriceExcel
wb = load_workbook(filepath)
# select AMZNPriceExcel sheet
sheet = wb.active
#adding line in spreadsheet
sheet.append([today,now,cotationae,monae,totactdol,totacteur,totcourt,portcourt,valimp,monimp,cashdisp])
# save workbook
wb.save(filepath)
#======================================================================================================
#ploting datas
#=====================================================================================================
#sending e-mail when value of portfolio reach a chosen amount
#=====================================================================================================
#sending SMS when portfolio amount reach a chosen amount
#================================================================================================
#adding condition to stop loop
#not using input because that stop program waiting fro answer. I want it ti work all time except if I break the loop
print('Do you want to stop App ?')
# add time.sleep to create a waiting time
time.sleep(300)
#if CTRL-C pressed then that breaks loop
except KeyboardInterrupt:
print('\nDone.')
z=input('xhat do you want to do ?')
print(z)
#must add a command to close windows
#the end of Version 2
#be careful to load package (file/setup/project/project interpreter)
#note that export CSV and excel are using 2 different module with 2 different way/syntax to manage data