Python 2.7 to exe using py2exe issue - python

I successfully created an .exe using py2exe with a simple test script I found on a tutorials website. The script I am using, however, does not seem to work. My code uses the csv module and dict reader with two .csv inputs.
I run the python setup.py p2exe command, and I get a flash of a command prompt, but that disappears before I can read anything on it. And once it disappears, I do not have the correct .csv file output that I would get if I just ran the script in python.
Can anyone offer any advice or things to try? Or is there a way I could get that pesky cmd window to stay open long enough for me to see what it says?
Thanks. My script is below.
import csv
def main():
iFileName = 'DonorsPlayTesting.csv'
oFileName = iFileName[:-4] + '-Output' + iFileName[-4:]
iFile = csv.DictReader(open(iFileName))
oFile = csv.writer(open(oFileName, 'w'), lineterminator = '\n')
iDirectory = csv.DictReader(open("DonorsDirectory.csv"))
oNames = {}
directory = {}
for line in iDirectory:
directory[line['Number']] = line['Name']
for key in directory.keys():
oNames[directory[key]] = 0
out_header = ['Name', 'Plays']
oFile.writerow(out_header)
for line in iFile:
if line['Type'] == "Test Completion":
if line['Number'] in directory:
oNames[directory[line['Number']]] += 1
elif line['Number'] not in directory:
oNames[line['Number']] = 'Need Name'
oFile.writerows(oNames.items())
main()

Related

file upload from container using webdav results into empty file upload

I'm attempting to wrap my brain around this because the identical code generates two different sets of outcomes, implying that there must be a fundamental difference between the settings in which the code is performed.
This is the code I use:
from webdav3.client import Client
if __name__ == "__main__":
client = Client(
{
"webdav_hostname": "http://some_address"
+ "project"
+ "/",
"webdav_login": "somelogin",
"webdav_password": "somepass",
}
)
ci = "someci"
version = "someversion"
directory = f'release-{ci.replace("/", "-")}-{version}'
client.webdav.disable_check = (
True # Need to be disabled as the check can not be performed on the root
)
f = "a.rst"
with open(f, "r") as fh:
contents = fh.read()
print(contents)
evaluated = contents.replace("#PIPELINE_URL#", "DUMMY PIPELINE URL")
with open(f, "w") as fh:
fh.write(evaluated)
print(contents)
client.upload(local_path=f, remote_path=f)
The file a.rst contains some text like:
Please follow instruction link below
#####################################
`Click here for instructions <https://some_website>`_
When I execute this code from macOS, a file with the same contents of a.rst appears on my website.
When I execute this script from within a container with a base image of Python 3.9 and the webdav dependencies, it creates a file on my website, but the content is always empty. I'm not sure why, but it could have something to do with the fact that I'm running it from within a Docker container that on top of it can't handle the special characters in the file (plain text seems to work though)?
Anyone have any ideas as to why this is happening and how to fix it?
EDIT:
It seems that the character ":" is creating the problem..

Python script not working as intended when called by task scheduler

I'm a beginner at Python and this site. Sorry if this might be simple.
I have modified a python script that calculates the amount of words in a pdf file "Master.pdf" an writes the time and date plus the amount of words to a .txt file.
I have Python2.7 installed, I have installed Anancoda and I am using the PyCharm editor. When I open my PyCharm editor and run this script, no problems arise, the script executes and everything works.
As I would like this script to run every 15 minutes, I have made it a task using Task Scheduler. The task is "Start a program" the program is:
- C:\Users\alkare\AppData\Local\Continuum\anaconda2\python.exe - and the argument is - "C:/Users/alkare/Desktop/Report/WordCount.py" -.
whenever it runs I see the command prompt open, some text fly across my screen and then the command line terminal closes, BUT no changes are done to my .txt file.
here is the code I am using saved as "WordCount.py":
#!/usr/bin/env python2.7
import os
import sys
import re
import datetime
import PyPDF2
def getPageCount(pdf_file):
pdfFileObj = open(pdf_file, 'rb')
pdfReader = PyPDF2.PdfFileReader(pdfFileObj)
pages = pdfReader.numPages
return pages
def extractData(pdf_file, page):
pdfFileObj = open(pdf_file, 'rb')
pdfReader = PyPDF2.PdfFileReader(pdfFileObj)
pageObj = pdfReader.getPage(page)
data = pageObj.extractText()
return data
def getWordCount(data):
data = data.split()
return len(data)
def main():
pdfFile = 'Master.pdf'
# get the word count in the pdf file
totalWords = 0
numPages = getPageCount(pdfFile)
for i in range(numPages):
text = extractData(pdfFile, i)
totalWords += getWordCount(text)
Now = datetime.datetime.now().strftime("%Y%m%d-%H%M%S")
f = open("TrackingTimeData.txt", "a")
f.write(Now[0:4] + "\t" + Now[4:6] + "/" + Now[6:8] + "\t" + Now[9:11] + ":" + Now[11:13] + "\t" + str(totalWords) + "\n")
f.close()
if __name__ == '__main__':
main()
The problem is that you are allowing the program to fail without providing you any meaningful output (it sounds like it hits an exception and closes).
Instead of just calling main() without guarding it in a try block:
if __name__ == '__main__':
main()
give yourself some slack here to gather information:
if __name__ == '__main__':
try:
main()
except Exception as e:
print("Error {}".format(e))
# drop into a command-prompt debugger:
import pdb
pdb.set_trace()
# slightly more old-school, pause the window to read the exception:
import time
time.sleep(15)
# throwback to DOS windows
import os
os.system('pause')
# read the error, come back to stackoverflow and describe the problem more, etc.
For example, mixing this with task scheduler, you'd want to right-click on your python.exe in Windows, go to properties, set "Run as Administrator" because maybe you're getting an access denied trying to read/write to a .PDF in some special directory. This is just an example of the many guesses people could throw in to randomly help you solve an issue versus knowing exactly what the error is.

Run script on multiple files sequentially?

I have this code which along with the rest of it runs on a single file in a folder.
I want to try and run this code on 11 files in the folder. I have to pass parameters to the whole script via an .sh script which I've written.
I've searched on here and found various solutions which have not worked.
def get_m3u_name():
m3u_name = ""
dirs = os.listdir("/tmp/")
for m3u_file in dirs:
if m3u_file.endswith(".m3u") or m3u_file.endswith(".xml"):
m3u_name = m3u_file
return m3u_name
def remove_line(filename, what):
if os.path.isfile(filename):
file_read = open(filename).readlines()
file_write = open(filename, 'w')
for line in file_read:
if what not in line:
file_write.write(line)
file_write.close()
m3ufile = get_m3u_name()
I have tried a different method of deleting the file just processed then looping the script to run again on the next file as I can do this manually but when I use
os.remove(m3ufile)
I get file not found either method of improving my code would be of great help to me. I'm just a newbie at this but pointing me in the right direction would be of great help.

Python convert txt file to pdf

I was wondering what would be simplest way to convert txt files in path batch convert to PDF?
I've looked into this in Python https://github.com/baruchel/txt2pdf
but I can't seem to call txt2pdf in terminal after importing it.
Any other suggestions?
Something like:
text_file = open(filename, 'r')
i = 0
for item in text_file:
i += 1
f = open("c:\\workspace\\{0}.txt".format(i), 'w')
txt2pdf convert (whatever goes here)
if i == 7:
break
also tried this using ReportLab
def hello(c):
ic = 0
c = open("c:\\workspace\\simple\\{0}.txt".format(ic), 'w')
for item in c:
ic += 1
c = canvas.Canvas("c:\\workspace\\simple\\{0}.pdf".format(ic))
hello(c)
c.showPage()
c.save()
if ic == 7:
break
not sure you already found the solution or not, just happen to see this question when I also searching the answer for related to your question.
You can just run as below if you are in terminal:
python txt2pdf.py yourfile.txt
## Make sure the txt2pdf.py is at your working environment and also the .txt too
Or if you run in jupyter notebook, just run as below:
run txt2pdf.py yourfile.txt
Thank you.
Go here to see how click this
This is the code after you installed pdfkit as the post of the link above shows
# from txt to html
# install wkthtml
import os
import pdfkit
with open("text.txt") as file:
with open ("text.html", "w") as output:
file = file.read()
file = file.replace("\n", "<br>")
output.write(file)
pdfkit.from_file("text.html", "output.pdf")
os.startfile("output.pdf")

Python will run in Unix, not Windows. How can you run an external python command in terminal?

I am trying to run some code in iPython which
will read in a tsv as a list,
go through it row-by row,
run an external python command on each line,
save the output into a list
append this to our tsv at the end.
My code runs in a Unix environment, but I cannot make it run using iPython and Windows. The external function that I call will also work when called in a windows terminal, but not when called, as below, in an iPython notebook. What have I done wrong? What else can I try?
Here is my code :
import csv
import GetAlexRanking #External Method exposed here
import subprocess
import pandas as p
loadData = lambda f: np.genfromtxt(open(f,'r'), delimiter=' ')
with open('list.tsv','rb') as tsvin, open('output.csv', 'wb') as csvout:
tsvin = csv.reader(tsvin, delimiter='\t')
csvout = csv.writer(csvout)
for row in tsvin:
count = 0
url = str([row[count]])
cmd = subprocess.Popen("python GetAlexRanking.py " + url ,shell=True)
cmd_out, cmd_err = cmd.communicate()
cmd_string = str(cmd_out)
print ">>>>>>>URL : " + url + " " + cmd_string #testing
csvout.writerows(url + "\t" + cmd_string) #writing
count+=1
How can I make this code run using iPython in Windows? It currently gives no error but the cmd_out variable always prints "None" rather than a correct value - the python command isn't being run correctly (however it will work in a normal Python/Unix environment).
Edit: Also runs correctly when ran from Windows terminal.
use
subprocess.Popen([sys.executable, "GetAlexRanking.py", url])
and better pass os.abspath("GetAlexRanking.py") as argument.
>>> sys.executable
'C:\\Python27\\pythonw.exe'
can be used on Windows, Linux, Mac.

Categories

Resources