choose from a list
I'm new to programming and even newer to Python and would be grateful
for some help on what has been a tough problem for me. The project I
am working on is an electronic medical record using MySQL/Python. I'm
currrently working on a module that looks up a patient's name based on
input from the user.
My goal is a lookup based on the first 2 or 3 letters of the patient's
last name. The matching results would appear as numbered choices so
that the user would choose only a number to then access various parts
of the patient's record. The results might look like this for user
input "smi":
1 387 John Smith
2 453 Jane Smith
3 975 Joe Smithton
Here is a copy of what I have so far, name_lookup.py:
import MySQLdb
def name_find(namefrag):
conn = MySQLdb.connect(host = "localhost",
user = "root",
passwd = "n85",
db = "meds")
cursor = conn.cursor(MySQLdb.cursors.DictCursor)
cursor.execute("SELECT patient_ID, firstname, lastname FROM
demographics WHERE lastname LIKE '"+ str(namefrag)+"%'")
results = cursor.fetchall()
for row in results:
print "%s %s %s %s" % (row["patient_ID"],
row["firstname"], row["lastname"])
cursor.close()
conn.close()
Thanks in advance for any help.
Mike
--
http://mail.python.org/mailman/listinfo/python-list
Re: choose from a list
Thanks to both of you for the help. I made several of the changes you
suggested and am getting the results in the format I want, eg:
0 387 John Smith
1 453 Jane Smith
2 975 Joe Smithton
My plan at this point is, in addition to printing the results of the
query, to create a list with a matching index so the user can select a
name and I can store the patient_ID to get other parts of their
medical record. Does this sound reasonable?
My code now looks like this:
import MySQLdb
def name_find(namefrag):
conn = MySQLdb.connect(host = "localhost",
user = "root",
passwd = "Barron85",
db = "meds")
cursor = conn.cursor(MySQLdb.cursors.DictCursor)
cursor.execute("SELECT patient_ID, firstname, lastname FROM
demographics WHERE lastname LIKE '%s%%'" % (namefrag))
result = cursor.fetchall()
for index, row in enumerate(result):
print "%d %s %s %s" % (index, row["patient_ID"],
row["firstname"], row["lastname"])
#create list here
cursor.close()
conn.close()
Thanks again, Mike
--
http://mail.python.org/mailman/listinfo/python-list
Re: choose from a list
I didn't know "result" was a list! Can all that info be stored in a list? How do the columns work? I was curious to see what the data looked like but I can't seem to print "result" from the prompt. Do variables used inside functions live or die once the function executes? If they die, how do I get around this? I tried defining 'r = ""' in the module before the function and then using it instead of "result" but that didn't help. Mike -- http://mail.python.org/mailman/listinfo/python-list
Re: choose from a list
This is really remarkable. My previous experience with programming
was in VB for Applications; doing the same thing seemed much more
complicated. This little function is only about 15 lines of code and
it forms the basis for my entire application. With a few simple
modifications I'll be able to get anything out of the database with a
minimum of entries from the user.
It turns out that 'results' was a tuple of dictionaries. I got an
error trying to call the tuple; converting it to a list worked. Here
is the current function:
import MySQLdb
def name_find(namefrag):
conn = MySQLdb.connect(host = "localhost",
user = "root",
passwd = "Barron85",
db = "meds")
cursor = conn.cursor(MySQLdb.cursors.DictCursor)
cursor.execute("SELECT patient_ID, firstname, lastname FROM
demographics WHERE lastname LIKE '%s%%'" % (namefrag))
results = cursor.fetchall()
for index, row in enumerate(results):
print "%d %s %s %s" % (index, row["patient_ID"],
row["firstname"], row["lastname"])
indx = int(raw_input("Select the record you want: "))
results_list = list(results)
return results_list[indx]['patient_ID']
cursor.close()
conn.close()
This returns the patient_ID after selecting a name from the list, eg
615L. I'm not sure why the "L" is there but it shouldn't be hard to
remove. Mensanator, thanks a lot for your help. This has been quite
a lot to digest--huge leap in my understanding of Python.
Michael Barron
On Oct 31, 12:32 am, "[EMAIL PROTECTED]" <[EMAIL PROTECTED]> wrote:
> On Oct 30, 7:39?pm, barronmo <[EMAIL PROTECTED]> wrote:
>
> > I didn't know "result" was alist!
>
> I don't use MySQL but that's how others work.
> Eachlistitem is a record, each record a tuple
> of field values.
>
> > Can all that info be stored in alist?
>
> If you don't fetch too many records at once.
> This is a test of my word database using ODBC
> and MS-ACCESS (the SQL is very simple since
> all the actual work is done in MS-ACCESS, Python
> is just retrieving the final results).
>
> import dbi
> import odbc
> con = odbc.odbc("words")
> cursor = con.cursor()
> cursor.execute("SELECT * FROM signature_anagram_summary")
> results = cursor.fetchall()
>
> Here, results (the recipient of .fetchall) is alistof tuples.
> The contents are:
>
> [(9, 10, 'anoretics', '101010001110011100'),
> (9, 10, 'atroscine', '101010001110011100'),
> (9, 10, 'certosina', '101010001110011100'),
> (9, 10, 'creations', '101010001110011100'),
> (9, 10, 'narcotise', '101010001110011100'),
> (9, 10, 'ostracine', '101010001110011100'),
> (9, 10, 'reactions', '101010001110011100'),
> (9, 10, 'secration', '101010001110011100'),
> (9, 10, 'tinoceras', '101010001110011100'),
> (9, 10, 'tricosane', '101010001110011100')]
>
> > How do the columns work?
>
> I don't know, I don't get column names. It looked like
> from your example that you can use names, I would have
> to use indexes, such as results[3][2] to get 'creations'.
> Maybe MySQL returns dictionaries instead of tuples.
>
> > I was curious to see what the data
> > looked like but I can't seem to print "result" from the prompt. Do
> > variables used inside functions live or die once the function
> > executes?
>
> Yeah, they die. You would have to have the function return
> the resultslistand indx, then you could use it's contents
> as criteria for further queries.
>
> So you might want to say
>
> name_find_results,indx = name_find(namefrag)
>
> > If they die, how do I get around this?
>
> Add 'return results,indx' to the function. Or better still,
> just return the record the user selected
> return results[indx]
> You wouldn't need indx anymore since there's only 1 record.
>
> > I tried defining 'r
> > = ""' in the module before the function and then using it instead of
> > "result" but that didn't help.
>
> > Mike
--
http://mail.python.org/mailman/listinfo/python-list
global name is not defined
I'm getting an error msg I don't understand, "global name EMR_globals
is not defined", and could use some help.
I've separated the application I'm building into several modules. One
of the modules holds variables I need to pass from one module to
another and is called 'EMR_globals'. Several other modules hold
functions or user menus and then 'EMR_main' controls the initial user
interaction. I'm using MySQL to hold the data.
The initial connection to the database is done by 'EMR_main'.
Functions then define and close a cursor for various queries. The
connection variable, 'conn', is defined 'conn = "" ' in EMR_globals
and then used in EMR_main. Unfortunately when a module.function
attempts to use it I get the error msg.
Here is the source of the error, module 'name_lookup':
def name_find(namefrag):
cursor = EMR_globals.conn.cursor(MySQLdb.cursors.DictCursor)
cursor.execute("SELECT patient_ID, firstname, lastname FROM
demographics WHERE lastname LIKE '%s%%'" % (namefrag))
results = cursor.fetchall()
for index, row in enumerate(results):
print "%d %s %s %s" % (index, row["patient_ID"],
row["firstname"], row["lastname"])
indx = int(raw_input("Select the record you want: "))
results_list = list(results)
a = str(results_list[indx]['patient_ID'])
print 'You have chosen patient ID # ' + a
cursor.execute("SELECT * FROM demographics WHERE patient_ID = %s"
% (a,))
selected_pt = cursor.fetchall()
# if this query returns more than one record the following code will
fail I think
print menus.menu_demographics(selected_pt['firstname'],
selected_pt['lastname'],
selected_pt['address'],
selected_pt['city'],
selected_pt['state'],
selected_pt['zipcode'],
selected_pt['phonenumber'])
print menus.menu_pt_record
cursor.close()
Thanks for any help. Mike
--
http://mail.python.org/mailman/listinfo/python-list
Re: global name is not defined
Thanks, seems to be fixed with importing MySQLdb, menus, EMR_main, etc in the Name_find module. Is there a better way to do things? I thought I was avoiding using global variables by putting the shared ones in their own module. Thanks for the help. Mike -- http://mail.python.org/mailman/listinfo/python-list
wx.listctrl- insertstringitem not working
Newbie with problem. I'm trying to build a multicolumn list control
with wxPython and am having difficulty getting the data from my query
into each column. I'm getting the following error:
Traceback (most recent call last):
File "/home/mb/PyPrograms/EMRGUI/Selectable.py", line 115, in
Repository(None, -1, 'Repository')
File "/home/mb/PyPrograms/EMRGUI/Selectable.py", line 57, in
__init__
index = self.list.InsertStringItem(sys.maxint, i['patient_ID'])
File "/usr/lib/python2.5/site-packages/wx-2.8-gtk2-unicode/wx/lib/
mixins/listctrl.py", line 751, in __InsertStringItem_
index = self.InsertImageStringItem(index, label, 0)
File "/usr/lib/python2.5/site-packages/wx-2.8-gtk2-unicode/wx/
_controls.py", line 4716, in InsertImageStringItem
return _controls_.ListCtrl_InsertImageStringItem(*args, **kwargs)
TypeError: String or Unicode type required
The code I'm using is based on the wxPython tutorial at Zetcode:
#!/usr/bin/python
import wx
import sys
import MySQLdb
from wx.lib.mixins.listctrl import CheckListCtrlMixin,
ListCtrlAutoWidthMixin
conn = MySQLdb.connect(host = "localhost",
user = "root",
passwd = "Barron85",
db = "meds")
def name_find(namefrag):
cursor = conn.cursor(MySQLdb.cursors.DictCursor)
cursor.execute("SELECT patient_ID, firstname, lastname,
phonenumber, SSN, \
DOB FROM demographics WHERE lastname LIKE '%s%%'" %
(namefrag))
results = cursor.fetchall()
results_list = list(results)
return results_list
cursor.close()
class CheckListCtrl(wx.ListCtrl, CheckListCtrlMixin,
ListCtrlAutoWidthMixin):
def __init__(self, parent):
wx.ListCtrl.__init__(self, parent, -1, style=wx.LC_REPORT |
wx.SUNKEN_BORDER)
CheckListCtrlMixin.__init__(self)
ListCtrlAutoWidthMixin.__init__(self)
class Repository(wx.Frame):
def __init__(self, parent, id, title):
wx.Frame.__init__(self, parent, id, title, size=(850, 400))
panel = wx.Panel(self, -1)
vbox = wx.BoxSizer(wx.VERTICAL)
hbox = wx.BoxSizer(wx.HORIZONTAL)
leftPanel = wx.Panel(panel, -1)
rightPanel = wx.Panel(panel, -1)
self.log = wx.TextCtrl(rightPanel, -1, style=wx.TE_MULTILINE)
self.list = CheckListCtrl(rightPanel)
self.list.InsertColumn(0, 'Patient ID', width=100)
self.list.InsertColumn(1, 'Lastname', width=200)
self.list.InsertColumn(2, 'Firstname', width=125)
self.list.InsertColumn(3, 'Phone')
self.list.InsertColumn(4, 'SSN')
self.list.InsertColumn(5, 'DOB')
patients = name_find(str(raw_input('Select the first several letters
of the last name: ')))
for i in patients:
index = self.list.InsertStringItem(sys.maxint,
i['patient_ID'])
self.list.SetStringItem(index, 1, i['lastname'])
self.list.SetStringItem(index, 2, i['firstname'])
self.list.SetStringItem(index, 3, i['phonenumber'])
self.list.SetStringItem(index, 4, i['SSN'])
self.list.SetStringItem(index, 5, i['DOB'])
vbox2 = wx.BoxSizer(wx.VERTICAL)
sel = wx.Button(leftPanel, -1, 'Select All', size=(100, -1))
des = wx.Button(leftPanel, -1, 'Deselect All', size=(100, -1))
apply = wx.Button(leftPanel, -1, 'Apply', size=(100, -1))
self.Bind(wx.EVT_BUTTON, self.OnSelectAll, id=sel.GetId())
self.Bind(wx.EVT_BUTTON, self.OnDeselectAll, id=des.GetId())
self.Bind(wx.EVT_BUTTON, self.OnApply, id=apply.GetId())
vbox2.Add(sel, 0, wx.TOP, 5)
vbox2.Add(des)
vbox2.Add(apply)
leftPanel.SetSizer(vbox2)
vbox.Add(self.list, 1, wx.EXPAND | wx.TOP, 3)
vbox.Add((-1, 10))
vbox.Add(self.log, 0.5, wx.EXPAND)
vbox.Add((-1, 10))
rightPanel.SetSizer(vbox)
hbox.Add(leftPanel, 0, wx.EXPAND | wx.RIGHT, 5)
hbox.Add(rightPanel, 1, wx.EXPAND)
hbox.Add((3, -1))
panel.SetSizer(hbox)
self.Centre()
self.Show(True)
def OnSelectAll(self, event):
num = self.list.GetItemCount()
for i in range(num):
self.list.CheckItem(i)
def OnDeselectAll(self, event):
num = self.list.GetItemCount()
for i in range(num):
self.list.CheckItem(i, False)
def OnApply(self, event):
num = self.list.GetItemCount()
for i in range(num):
if i == 0: self.log.Clear()
if self.list.IsChecked(i):
self.log.AppendText(self.list.GetItemText(i) + '\n')
app = wx.App()
Repository(None, -1, 'Repository')
app.MainLoop()
If you see what I'm doing wrong I'd be grateful for any help.
Mike
--
http://mail.python.org/mailman/listinfo/python-list
Namespace troubles
I'm new to programming and new to Python; namespace issues are getting
the best of me. Can someone help me with the following:
import wx
import sys
sys.path.append('~/PyPrograms/EMRGUI')
import Selectable
class MyApp(wx.App):
def __init__(self):
wx.App.__init__(self)
frame = MyFrame(None, -1, 'EMR')#create instance of
MyFrame
frame.Show(True)#make visible and
center frame
frame.Centre()
class MyFrame(wx.Frame):
def __init__(self, parent, id, title):
wx.Frame.__init__(self, parent, id, title, size=(600,500))
nb = wx.Notebook(self) #create instance of
wx.Notebook
self.page1 = Form1(nb, -1) #create instance of
panel Form1 with
Notebook instance as parent
nb.AddPage(self.page1, "Choose Patient")#add the panels as
Notebook
pages
self.page1.SetFocus() #give focus to page 1
def patient_lookup(self, first_ltrs): #passes first letters of
last name and creates new page c results
self.page2 = Selectable.Repository(nb, -1, first_ltrs) #creates
instance of panel Repository from Selectable mod
nb.AddPage(self.page2, "Patient Lookup")#adds second page with
results
self.page2.SetFocus() #give focus to new page
class Form1(wx.Panel):
def __init__(self, parent, id):
wx.Panel.__init__(self, parent, id) #inherits from wx.Panel
f = wx.GetTopLevelParent(self)
self.button = wx.Button(self, 10, "Search", wx.Point(200,
325)) #create instance of wx.Button
wx.Button.SetTransparent(self.button, 100)
#experiment with
SetTransparent method
self.lblname = wx.StaticText(self, -1, "Enter first letters of
last name:",wx.Point(20,60))
self.editname = wx.TextCtrl(self, 20, "", wx.Point(150, 60),
wx.Size(140,-1))
wx.EVT_BUTTON(self, 10, f.patient_lookup(self.editname.Value))
#calls function to get list of patients
app = MyApp() #create instance of
MyApp
app.MainLoop() #run program
I'm getting an error from the patient_lookup function: "global name
'nb' is not defined". I don't understand how a function in the same
class cannot see the wx.Notebook instance "nb". I know it exists
somewhere I just haven't found the name for it. I've tried
"frame.nb", "self.nb", f = GetTopLevelParent(self) then f.nb. How can
an instance of something just disappear?
Thanks for any help.
Mike
--
http://mail.python.org/mailman/listinfo/python-list
Re: Namespace troubles
Mike and Alan, thanks very much, working fine now. I'll review the classes references too. Mike -- http://mail.python.org/mailman/listinfo/python-list
problem parsing lines in a file
I'm having difficulty getting the following code to work. All I want
to do is remove the '0:00:00' from the end of each line. Here is part
of the original file:
3,3,"Dyspepsia NOS",9/12/2003 0:00:00
4,3,"OA of lower leg",9/12/2003 0:00:00
5,4,"Cholera NOS",9/12/2003 0:00:00
6,4,"Open wound of ear NEC*",9/12/2003 0:00:00
7,4,"Migraine with aura",9/12/2003 0:00:00
8,6,"HTN [Hypertension]",10/15/2003 0:00:00
10,3,"Imerslund syndrome",10/27/2003 0:00:00
12,4,"Juvenile neurosyphilis",11/4/2003 0:00:00
13,4,"Benign paroxysmal positional nystagmus",11/4/2003 0:00:00
14,3,"Salmonella infection, unspecified",11/7/2003 0:00:00
20,3,"Bubonic plague",11/11/2003 0:00:00
output = open('my/path/ProblemListFixed.txt', 'w')
for line in open('my/path/ProblemList.txt', 'r'):
newline = line.rstrip('0:00:00')
output.write(newline)
output.close()
This result is a copy of "ProblemList" without any changes made. What
am I doing wrong? Thanks for any help.
Mike
--
http://mail.python.org/mailman/listinfo/python-list
Re: problem parsing lines in a file
Thanks everyone. I learned several things on this one. I ended up using the .replace() method and got the results I wanted. Thanks again, Michael Barron -- http://mail.python.org/mailman/listinfo/python-list
subtract dates with time module
I'm trying to get the difference in dates using the time module rather
than datetime because I need to use strptime() to convert a date and
then find out how many weeks and days until that date. I'm a beginner
so any help would be appreciated. Here is the code:
def OBweeks(ptID):
qry = 'SELECT short_des FROM problems WHERE patient_ID = %s;' %
(ptID)
results = EMR_utilities.getAllData(qry)
for items in results:
r = re.search('\d\d\d\d-\d\d-\d\d', items)
if r:
d = time.strptime(r.group(), "%Y-%m-%d') -
time.localtime()
weeks, days = divmod(d.days, 7)
return '%s %s/7 weeks' % (weeks, days)
This isn't working. I'm getting "unsupported operand type for -:
'time.struct_time' and 'time.struct_time" error.
Thanks, Mike
--
http://mail.python.org/mailman/listinfo/python-list
Re: subtract dates with time module
Thanks for the help everyone. I ended up with the following:
def OBweeks(ptID):
qry = 'SELECT short_des FROM problems WHERE patient_ID = %s;' %
(ptID)
results = EMR_utilities.getAllData(qry)
for items in results:
r = re.search('\d\d\d\d-\d\d-\d\d', str(items))
if r:
edc = datetime.date(*map(int, r.group().split('-')))
pregnancy = datetime.timedelta(weeks=-40)
conception = edc + pregnancy
howfar = datetime.date.today() - conception
weeks, days = divmod(howfar.days, 7)
return '%s %s/7 weeks' % (weeks, days)
else: pass
Mike
--
http://mail.python.org/mailman/listinfo/python-list
print some text
I'm a beginner searching for an easy way to print the contents of a text control. So far I've come up with the following(difficulties): 1) using wxPython -convert to HTML and then print (I don't know anything about HTML) -use wx.Printout (Seems complicated; may be beyond my abilities) 2) create a text file and then print it out (can create but can only print with the win32api.ShellExecute method so this solution doesn't help me on my Linus laptop) 3) use ReportLab to create .pdf and then print that out (again, can create but can't print in Linux) Thanks for any help. Mike -- http://mail.python.org/mailman/listinfo/python-list
Re: print some text
On Apr 25, 2:44 pm, "Gabriel Ibanez" <[EMAIL PROTECTED]> wrote:
> Hi !
>
> Other idea (old style school):
>
> def printing():
>f=open("lpt1", "w")
>f.write("\nSomething to print\f")
>f.close()
>
> Cheers..
>
> - Ibanez -
>
I haven't found a way from within python to print f. I'm sure there
it is something simple but I've been searching for a couple weeks now
with no luck.
Mike
--
http://mail.python.org/mailman/listinfo/python-list
python-imaging-sane
I'm trying to get my application to scan, create a .pdf, and then save
it in a patient's folder. I found python-imaging-sane but I can't get
things to work correctly. Here is what's happening at the command
prompt:
import sane
sane.init()
(16777235, 1, 0, 19)
print sane.get_devices()
[('canondr:libusb:001:002', 'Canon', 'P-150', 'sheetfed scanner')]
s = sane.open(sane.get_devices()[0][0])
s.start()
i = s.snap()
Traceback (most recent call last):
File "", line 1, in
File "/usr/lib/python2.6/dist-packages/sane.py", line 243, in snap
self.dev.snap( im.im.id, no_cancel )
_sane.error: Operation was cancelled
Ultimately I would like to get it to scan duplex and do multipage
docs. Thanks for any help.
Mike Barron
--
http://mail.python.org/mailman/listinfo/python-list
