Python try finally statement to run another file - python

I am having an issue getting my try and finally statement to execute properly. I am trying to get another Python file to execute once a user has interacted with the first program.For example, once the first program is run the user will be asked to scan their tag which will create a unique user id for that user; after their tag is scanned a second python file will be executed. My problem is that the second file is constantly being run as soon as the first file is executed regardless if the tag is scanned first or not. I have added my code below with comments to help explain better. Any thoughts?
import RPi.GPIO as GPIO
from mfrc522 import SimpleMFRC522
# Second File being ran
import medform
reader = SimpleMFRC522()
try:
# user id being created
c = string.ascii_letters + string.digits
op = "".join(choice(c) for x in range(randint(8,16)))
# Printed before tag is scanned
print("Please Scan tag " )
reader.write(op + op)
# if tag is scanned / id created open second file
if reader.write(op + op):
os.system('python medform.py')
else:
print("Scan Tag First" )
# Print after tag is scanned
print("Scan Complete")
finally:
GPIO.cleanup()

importing a file runs it, there are 2 ways to do what you want:
import the file when you want it to run
define a main function in the other file that you can run from the first one instead of having all the code in the top level
the second option is the best one in most cases, as you normally would not want a file to actually do stuff on import.
so in the second file you would have:
def main():
# the code you want to run (make sure to indent it)
then in the first you can have:
import medform
# ...
medform.main()

Related

Using win32com to download attachments through outlook with python

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.

Python Syntax Error "Expected indented block"

I would just like to ask for help regarding my code as it is giving me an error which I cannot see. Normally, IDLE would highlight the error but this time, it's not giving me any at all so I am quite confused on where my problem is located.
Also just a headsup, I am quite new to python and have just recently tried it out about 2 days ago so I would be thankful if anyone could help this noob(me) with this problem.
import time as t
from os import path
##dest is the string
def createFile(dest):
'''
The script creates a text at the passed in location, names file based on date
'''
date = t.localtime(t.time())
##name=month/day/year
name = '%d_%d_%d.txt'%(date[1],date[2],(date[0]%100))
##if file does not exist
if not(path,isfile(dest+name)):
f = open(dest + name, 'w')
f.write('\n'*30)
f.close()
if __name__=='__main__':
destination = 'C:\\Python34\\My Projects in Python\\'
createFile(destination)
input("done!")
You had couple of issues in your code:
You need to indent the comment as well
You need to move back the name
You need to put path.isfile instead of path,isfile
You need to indent 3 lines after your first if
Here's working code:
import time as t
from os import path
##dest is the string
def createFile(dest):
'''
The script creates a text at the passed in location, names file based on date
'''
date = t.localtime(t.time())
##name=month/day/year
name = '%d_%d_%d.txt'%(date[1],date[2],(date[0]%100))
##if file does not exist
if not(path.isfile(dest+name)):
f = open(dest + name, 'w')
f.write('\n'*30)
f.close()
if __name__=='__main__':
destination = 'C:\Python34\My Projects in Python\'
createFile(destination)
input("done!")

Getting file input into Python script for praw script

So I have a simple reddit bot set up which I wrote using the praw framework. The code is as follows:
import praw
import time
import numpy
import pickle
r = praw.Reddit(user_agent = "Gets the Daily General Thread from subreddit.")
print("Logging in...")
r.login()
words_to_match = ['sdfghm']
cache = []
def run_bot():
print("Grabbing subreddit...")
subreddit = r.get_subreddit("test")
print("Grabbing thread titles...")
threads = subreddit.get_hot(limit=10)
for submission in threads:
thread_title = submission.title.lower()
isMatch = any(string in thread_title for string in words_to_match)
if submission.id not in cache and isMatch:
print("Match found! Thread ID is " + submission.id)
r.send_message('FlameDraBot', 'DGT has been posted!', 'You are awesome!')
print("Message sent!")
cache.append(submission.id)
print("Comment loop finished. Restarting...")
# Run the script
while True:
run_bot()
time.sleep(20)
I want to create a file (text file or xml, or something else) using which the user can change the fields for the various information being queried. For example I want a file with lines such as :
Words to Search for = sdfghm
Subreddit to Search in = text
Send message to = FlameDraBot
I want the info to be input from fields, so that it takes the value after Words to Search for = instead of the whole line. After the information has been input into the file and it has been saved. I want my script to pull the information from the file, store it in a variable, and use that variable in the appropriate functions, such as:
words_to_match = ['sdfghm']
subreddit = r.get_subreddit("test")
r.send_message('FlameDraBot'....
So basically like a config file for the script. How do I go about making it so that my script can take input from a .txt or another appropriate file and implement it into my code?
Yes, that's just a plain old Python config, which you can implement in an ASCII file, or else YAML or JSON.
Create a subdirectory ./config, put your settings in ./config/__init__.py
Then import config.
Using PEP-18 compliant names, the file ./config/__init__.py would look like:
search_string = ['sdfghm']
subreddit_to_search = 'text'
notify = ['FlameDraBot']
If you want more complicated config, just read the many other posts on that.

QPrinter doesn't print more than once

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.

try: and exception: error

So i am working on this code below. It complied alright when my Reff.txt has more than one line. But it doesnt work when my Reff.txt file has one line. Why is that? I also wondering why my code doesn't run "try" portion of my code but it always run only "exception" part.
so i have a reference file which has a list of ids (one id per line)
I use the reference file(Reff.txt) as a reference to search through the database from the website and the database from the server within my network.
The result i should get is there should be an output file and file with information of that id; for each reference id
However, this code doesn't do anything on my "try:" portion at all
import sys
import urllib2
from lxml import etree
import os
getReference = open('Reff.txt','r') #open the file that contains list of reference ids
global tID
for tID in getReference:
tID = tID.strip()
try:
with open(''+tID.strip()+'.txt') as f: pass
fileInput = open(''+tID+'.txt','r')
readAA = fileInput.read()
store_value = (readAA.partition('\n'))
aaSequence = store_value[2].replace('\n', '') #concatenate lines
makeList = list(aaSequence)#print makeList
inRange = ''
fileAddress = '/database/int/data/'+tID+'.txt'
filename = open(fileAddress,'r')#name of the working file
print fileAddress
with open(fileAddress,'rb') as f:
root = etree.parse(f)
for lcn in root.xpath("/protein/match[#dbname='PFAM']/lcn"):#find dbname =PFAM
start = int(lcn.get("start"))#if it is PFAM then look for start value
end = int(lcn.get("end"))#if it is PFAM then also look for end value
while start <= end:
inRange = makeList[start]
start += 1
print outputFile.write(inRange)
outputFile.close()
break
break
break
except IOError as e:
newURL ='http://www.uniprot.org/uniprot/'+tID+'.fasta'
print newURL
response = urllib2.urlopen(''+newURL) #go to the website and grab the information
creatNew = open(''+uniprotID+'.txt','w')
html = response.read() #read file
creatNew.write(html)
creatNew.close()
So, when you do Try/Except - if try fails, Except runs. Except is always running, because Try is always failing.
Most likely reason for this is that you have this - "print outputFile.write(inRange)", but you have not previously declared outputFile.
ETA: Also, it looks like you are only interested in testing to the first pass of the for loop? You break at that point. Your other breaks are extraneous in that case, because they will never be reached while that one is there.

Categories

Resources