I created a code that use Google Books API on Jupiter in python language. I would like to create an .exe file in order to use it on other PCs. I did it with pyinstaller name_of_the_script.py, but when I execute it after I entered the second input, the command window disappears without showing outputs, also if I put an input line at the end in order to keep alive the script until I press a key.
Here the code:
import requests
quote = input('Inserisci la citazione: ')
lingua = input('\nInserisci lingua (sigla, ad esempio ''it'' per ''Italiano''): ')
key = 'xxxxxxxxx'
parms = {'q':quote, 'key':key, 'maxResults':5,'langRestrict':lingua}
r = requests.get(url='https://www.googleapis.com/books/v1/volumes', params = parms)
rj = r.json()
for i in range(0,3):
print('\n' + rj['items'][i]['volumeInfo']['title'] + '\n')
for authors in rj['items'][i]['volumeInfo']['authors']:
print(authors)
print('\n' + '\n')
input('press enter to quit')
What is wrong?
I solved!
It was an error in the conversion of the .ipynb file into .py file.
To convert it I used a code found here in SO and now it works.
Here the post that helped me:
Is it possible to generate an executable (.exe) in a jupyter-notebook?
Related
I've written a short code to download and rename files from a specific folder in my outlook account. The code works great, the only problem is that I typically need to run the code several times to actually download all of the messages. It seems the code is just failing to acknowledge some of the messages, there are no errors when I run through it.
I've tried a few things like walking through each line step by step in the python window, running the code with outlook closed or opened, and trying to print the files after they're successfully saved to see if there are specific messages that are causing the problem.
Here's my code
#! python3
# downloadAttachments.py - Downloads all of the weight tickets from Bucky
# Currently saves to desktop due to instability of I: drive connection
import win32com.client, os, re
#This line opens the outlook application
outlook = win32com.client.Dispatch("Outlook.Application").GetNamespace("MAPI")
#Not exactly sure why the inbox is default folder 6 but it works
inbox = outlook.GetDefaultFolder(6)
#box where the messages are to save
TicketSave = inbox.Folders('WDE').Folders('SAVE').Folders('TicketSave')
#box where the messages are moved to
done = inbox.Folders('WDE').Folders('CHES').Folders('Weight Tickets')
ticketMessages = TicketSave.Items
#Key is used to verify the subject line is correct. This script only works if the person sends
# their emails with a consistent subject line (can be altered for other cases)
key = re.compile(r'wde load \d{3}') #requires regulars expressions (i.e. 'import re')
for message in ticketMessages:
#will skip any message that does not match the correct subject line format (non-case sensitive)
check = str(message.Subject).lower()
if key.search(check) == None:
continue
attachments = message.Attachments
tic = attachments.item(1)
ticnum = str(message.Subject).split()[2]
name = str(tic).split()[0] + ' ticket ' + ticnum + '.pdf' #changes the filename
tic.SaveAsFile('C:\\Users\\bhalvorson\\Desktop\\Attachments' + os.sep + str(name))
if message.UnRead == True:
message.UnRead = False
message.Move(done)
print('Ticket pdf: ' + name + ' save successfully')
Alright I found the answer to my own question. I'll post it here in case any other youngster runs into the same problem as me.
The main problem is the "message.Move(done)" second from the bottom.
Apparently the move function alters the current folder thus altering the number of loops that the for loop will go through. So, the way it's written above, the code only ever processes half of the items in the folder.
An easy work around is to switch the main line of the for loop to "for message in list(ticketMessages):" the list is not affected by the Move function and therefore you'll be able to loop through every message.
Hope this helps someone.
In Python 2.7, using Selenium, I want the script to open the 'masters.txt' file. Then, go to Twitter (while logged in beforehand), and post the line like so:
driver.get("https://twitter.com")
elem = driver.find_element_by_name('tweet')
elem.send_keys(line1 + " #worked")
elem = driver.find_element_by_xpath('//*[#id="timeline"]/div[2]/div/form/div[2]/div[2]/button')
elem.send_keys(Keys.RETURN)
then, the same, except:
elem.send_keys(line2 + " #worked")
then, the same, except:
elem.send_keys(line3 + " #worked")
etc...
So, load every single line & tweet it + "with another text I've added". How is that possible?
Thanks in advance! :)
EDIT: Example of 'master.txt' (text file) contents:
test
blablabla
awesome
This is an awesome Tweet
something
another line
etc...
What I've tried:
f = open("masters.txt")
lines = f.readlines()
for line in lines:
elem.send_keys(line + " #worked")
However that doesn't exactly work and messes it up etc... If someone could complete my code and write me what I'm looking for, that would be great! :)
I'm writing a script that will find out what router model and what IOS version a Cisco router is using. I'm writing it in Python using the SecureCRT api. The script sends a show version command that displays information about the router, including the information I need. I then use the SecureCRT api to pull all of that text from the application screen and then I iterate through the text to and use if statements to match router models to see which one it is. Everytime i run the script it runs and doesnt error out but the "new.txt" file is blank.
# $language = "python"
# $interface = "1.0"
crt.Screen.Synchronous = True
ModelIOSScreen = ""
def Main():
ModelIOS()
def ModelIOS():
crt.Screen.Send("show version" + chr(13))
crt.Screen.WaitForString(">")
Screen = crt.Screen.Get(-1, 1, 50, 70)
ModelIOSScreen = str(Screen.split(" ", -1))
RouterModel = ""
for word in ModelIOSScreen:
if word == "2811":
RouterModel = "2811"
elif word == "2801":
RouterModel = "2801"
elif word == "CISCO2911/K9":
RouterModel = "2911"
file = open("new.txt", "w")
file.write(ModelIOSScreen)
I'm on my phone and could probably write a better answer, but I'm about to go to bed. You never close the file you open. Using the following works better.
with open(file, "w") as fp:
fp.write(variable)
We have an AJA Ki Pro recorder at another location and I a need to created an automated system that pulls the recorded files over to my editing studio. So far I have successfully been able to pull recordings using a python script run via an Applescript through Automator. I than can trigger the application from iCal. Basically my script involves setting the "MediaState" parameter on my recorder to "Data" (value=1) so I can pull files, comparing the files on the recorder to my local files (it only downloads what I dont already have locally), and then setting the "MediaState" property back to "Rec" (value=0) so the recorder is ready to go again.
Here are the 2 problems I have been unable to resolve so far. Bear with me, I have about 2 days worth of experience with Python :) It seems that I have somehow created a loop where it constantly says "Looking for new clips" and "No new clips found". Ideally I would like to have the script terminate if no new clips are found. I would also like to set this up so that when it finishes a download through cURL, it automatically sets my "MediaState" back to value=0 and ends the script. Here is my code so far:
# This script polls the unit downloads any new clips it hasn't already downloaded to the current directory
# Arguments: hostname or IP address of Ki Pro unit
import urllib, sys, string, os, posix, time
def is_download_allowed(address):
f = urllib.urlopen("http://"+address+"/config?action=get¶mid=eParamID_MediaState")
response = f.read()
if (response.find('"value":"1"') > -1):
return True
f = urllib.urlopen("http://"+address+"/config?action=set¶mid=eParamID_MediaState&value=1")
def download_clip(clip):
url = "http://" + address + "/media/" + clip
print url
posix.system("curl --output " + clip + " " + url);
def download_clips(response):
values = response.split(":")
i = 0
for word in values:
i += 1
if(word.find('clipname') > -1):
clip = values[i].split(',')[0].translate(string.maketrans("",""), '[]{} \,\"\" ')
if not os.path.exists(clip):
print "Downloading clip: " + clip
download_clip(clip)
else:
f = urllib.urlopen("http://"+address+"/config?action=set¶mid=eParamID_MediaState&value=0")
print "No new clips found"
address = sys.argv[1]
while 1:
if (is_download_allowed(address)):
print "Looking for new clips"
f = urllib.urlopen("http://"+address+"/clips")
response = f.read()
download_clips(response)
If the download_clips function is looping through the clip names, why you need that infinite while 1 loop? I think it is not necessary. Just remove it and dedent the block.
In my application I have a method for users to convert a report to a PDF document. This works perfectly - once. If the user clicks the button again, the conversion hangs.
This is my code:
def print_report(self):
web = QtWebKit.QWebView()
filename = "reporttemplate.html"
file = open(filename,'r')
html = file.read()
file.close()
web.setHtml(html)
#web.show()
printer = QtGui.QPrinter()
printer.setPageSize(QtGui.QPrinter.Letter)
printer.setOutputFormat(QtGui.QPrinter.PdfFormat)
# ---- BROKEN ----
# This next line is where it hangs on the second call to this function.
# The first time it works, and generates the PDF as expected.
# ---- BROKEN ON THE NEXT LINE! ----
printer.setOutputFileName(r'C:\path\to\report\directory\file.pdf')
def convertIt():
web.print_(printer)
print "Pdf generated"
web.close()
QtCore.QObject.connect(web, QtCore.SIGNAL("loadFinished(bool)"), convertIt)
My thought is that the printer still has the file open. If that's the case, how can I close the file?
It works if I relaunch the application and the file already exists. For that reason, I don't believe it's hanging because the file already exists.
Testing your code I noticed that for me it only works when I put web.setHtml(html) at the end (last statement) in the print_report method. Doing that I was able to generate file.pdf as many times as I wanted to.