[issue33011] Embedded 3.6.4 distribution does not add script parent as sys.path[0]
Change by Cong Monkey <congzhan...@gmail.com>: -- components: +Windows nosy: +paul.moore, steve.dower, tim.golden, zach.ware type: -> behavior ___ Python tracker <rep...@bugs.python.org> <https://bugs.python.org/issue33011> ___ ___ Python-bugs-list mailing list Unsubscribe: https://mail.python.org/mailman/options/python-bugs-list/archive%40mail-archive.com
[issue33011] Embedded 3.6.4 distribution does not add script parent as sys.path[0]
New submission from Cong Monkey <congzhan...@gmail.com>: Embedded 3.6.0 distribution does not insert script parent in sys.path[0], but the normal python do it. this make some failed, like when I try to do pip install future, it will failed as import src.future failed, which works for normal python. The root source maybe when python36._pth exist, python rewrite the flag and mark as isolate mode automate, which will not update sys.path when pymain_init_sys_path. I use a trick which is really bad as a work around(and even when site .main the sys.argv is not ready!), and hope upstream will fix the root source. ===begin in my usercustomize.py: import sys import pathlib class DummyImportHook(object): def __init__(self, *args): self.is_script_path_to_sys_path_be_done = False pass def find_module(self, fullname, path=None): # print(f'{DummyImportHook.__name__} trigger {sys.argv if hasattr(sys, "argv") else ""} ') if not self.is_script_path_to_sys_path_be_done and hasattr(sys, 'argv'): if sys.argv[0] is not None: # print(f'{DummyImportHook.__name__}:argv is {sys.argv}') path_obj = pathlib.Path(sys.argv[0]) # #if path_obj.exists(): # print(f'{DummyImportHook.__name__}:I am try to add {str(path_obj.parent)} to sys.path') sys.path.insert(0, str(path_obj.parent)) print(f'{DummyImportHook.__name__}:current sys.path is {sys.path}') pass self.is_script_path_to_sys_path_be_done = True pass return None pass print(f'{DummyImportHook.__name__}:auto script path to sys.path hook load!') #sys.meta_path = [DummyImportHook()] sys.meta_path.insert(0,DummyImportHook()) ===end in my usercustomize.py: ===begin in my python36._pth python36 . # Uncomment to run site.main() automatically import site ===end in my python36._pth BTW, where is Embedded distribution package script in python git repo? -- messages: 313316 nosy: Cong Monkey priority: normal severity: normal status: open title: Embedded 3.6.4 distribution does not add script parent as sys.path[0] versions: Python 3.6 ___ Python tracker <rep...@bugs.python.org> <https://bugs.python.org/issue33011> ___ ___ Python-bugs-list mailing list Unsubscribe: https://mail.python.org/mailman/options/python-bugs-list/archive%40mail-archive.com
py2exe with python 3.x
Hi, i wonderd if there is a way to convert a py-file to a exe-file with version 3.x of python. I know that it was possible till version 2.7.x. But is there a way to do it in version 3.x? Yours sincerely, Monkey -- http://mail.python.org/mailman/listinfo/python-list
CDA conversion
Good evening. I am trying to write an application in Python that will allow a person to insert a CD into their computer and this python script will convert the music to mp3. NOTE: I have already google'd this, and nothing really pops out at me. I found tons of applications that does this, but I am trying to write this myself (as a little project). Does anyone know a good site that I can find some pointers on getting started? The machine that this will run on is running Linux and has Python 2.5. Any help is greatly appreciated. ~ .dave Filize.com -- http://mail.python.org/mailman/listinfo/python-list
WXPython - Using inline images
I have a question about WXPython and using inline images. The code that I have included into this email comes from the following URL: http://www.daniweb.com/code/snippet654.html As you can see from the code below, that this application will take an inline JPG image, and will create a local copy of the image called zzz777.jpg. Is there anyway WXPython can just use the inline image without having to create a physical copy? I know this can be done in TKinter using inline gifs, but was wondering if anyone knew of a clever way to do this in WXPython? --- CODE -- import wx import cStringIO import base64 BG_Egypt_jpg_b64='''\ /9j/4AAQSkZJRgABAQAAAQABAAD/2wBDAAYEBQYFBAYGBQYHBwYIChAKCgkJChQODwwQFxQYGBcU FhYaHSUfGhsjHBYWICwgIyYnKSopGR8tMC0oMCUoKSj/2wBDAQcHBwoIChMKChMoGhYaKCgoKCgo KCgoKCgoKCgoKCgoKCgoKCgoKCgoKCgoKCgoKCgoKCgoKCgoKCgoKCgoKCj/wAARCAAgACADASIA AhEBAxEB/8QAHwAAAQUBAQEBAQEAAAECAwQFBgcICQoL/8QAtRAAAgEDAwIEAwUFBAQA AAF9AQIDAAQRBRIhMUEGE1FhByJxFDKBkaEII0KxwRVS0fAkM2JyggkKFhcYGRolJicoKSo0NTY3 ODk6Q0RFRkdISUpTVFVWV1hZWmNkZWZnaGlqc3R1dnd4eXqDhIWGh4iJipKTlJWWl5iZmqKjpKWm p6ipqrKztLW2t7i5usLDxMXGx8jJytLT1NXW19jZ2uHi4+Tl5ufo6erx8vP09fb3+Pn6/8QAHwEA AwEBAQEBAQEBAQECAwQFBgcICQoL/8QAtREAAgECBAQDBAcFBAQAAQJ3AAECAxEEBSEx BhJBUQdhcRMiMoEIFEKRobHBCSMzUvAVYnLRChYkNOEl8RcYGRomJygpKjU2Nzg5OkNERUZHSElK U1RVVldYWVpjZGVmZ2hpanN0dXZ3eHl6goOEhYaHiImKkpOUlZaXmJmaoqOkpaanqKmqsrO0tba3 uLm6wsPExcbHyMnK0tPU1dbX2Nna4uPk5ebn6Onq8vP09fb3+Pn6/9oADAMBAAIRAxEAPwB2taqm lRI7pAsCxQDi0WVizqo7KzEln9+v55f/AAlsZ/5dp+f+oI//AMa9/wDPc8c8wW3f97p3v/HD9f8A P66mtaqmlRI7pAsCxQDi0WVizqo7KzEln9+v5+J9+9tDQy/+EtjP/LtPz/1BH/8AjXv/AJ7x67q0 9xo8Lxp5AlurUc2ggk2mdAeCoYAgn6g9wea2r+Inv7aK3tILpZZLm3yV0t4fl85C2X8sYG3OeeQS O/N3xzzBbd/3une/8cP1/wA/qbWab36gHjnmC27/AL3Tvf8Ajh+v+f1PHPMFt3/e6d7/AMcP1/z+ uXr2sDV1hRIb553urU86fLGoVJYz3QKAFH+e+hresafcXapJDfSiHyDxYTsvmRhCOQhDAMo9QfcH k1te3W4Fu98UW0E/kQW8xWNEQkaQ7gsFAb5vLO75ieckHtnvia9rA1dYUSG+ed7q1POnyxqFSWM9 0CgBR/nvqf8ACWxn/l2n5/6gj/8Axr3/AM9z/hLYz/y7T8/9QR//AI17/wCe58mB/9k= ''' jpg1 = base64.b64decode(BG_Egypt_jpg_b64) # save the image to a file ... # (couldn't figure out any other way to use with wx.Bitmap) tile_file = zzz777.jpg fout = open(tile_file, wb) fout.write(jpg1) fout.close() self.bmp1 = wx.Bitmap(tile_file) wx.EVT_PAINT(self, self.on_paint) - -- http://mail.python.org/mailman/listinfo/python-list
POP3 - Saving an image attachment only.
I wrote some code below (Code1 block) which will read a pop3 email account and will open each email in the inbox. What I want my code to do is only pull the attachment; as you see below I basically output everything. Is there an easy way to just pull attachments? (NOTE, the only attachements that I want to pull are images) === I also tried this, but for some reason the part.get_filename Always equal None msg = email.message_from_string(mstring) for part in msg.walk(): fn = part.get_filename() if fn None: filenames.append(fn) attachedcontents.append(part.get_payload()) print im here *..::CODE1:.. ===* for email in items: id, size = string.split(email) resp, text, octets = server.retr(id) text = string.join(text, \n) file = StringIO.StringIO(text) message = rfc822.Message(file) print message.fp.read() *..::OUTPUT1::.. ===* --__CONTENT_64564_PART_BOUNDARY__33243242__ Content-Type: text/plain Content-Transfer-Encoding: quoted-printable X-MIME-Autoconverted: from 8bit to quoted-printable by njbrmotmta9.vzwpix.com id l7LIT1GZ008951 Some email text --__CONTENT_64564_PART_BOUNDARY__33243242__ Content-Type: image/jpeg; name=0815071408.jpg Content-ID: 0815071408.jpg Content-Location: 0815071408.jpg Content-Transfer-Encoding: base64 /9j/4AkjSkZYWAAQ/9j/2wCEABALDA4MChAODQ4SERATGCgaGBYWGDEjJR0oOjM9PDkzODdA SFxOQERXRTc4UG1RV19iZ2hnPk1xeXBkeFxlZ2MBERISGBUYLxoaL2NCOEJjY2NjY2NjY2Nj Y2NjY2NjY2NjY2NjY2NjY2NjY2NjY2NjY2NjY2NjY2NjY2NjY2NjY//EAaIAAAEFAQEBAQEB AAABAgMEBQYHCAkKCxAAAgEDAwIEAwUFBAQAAAF9AQIDAAQRBRIhMUEGE1FhByJx FDKBkaEII0KxwRVS0fAkM2JyggkKFhcYGRolJicoKSo0NTY3ODk6Q0RFRkdISUpTVFVWV1hZ WmNkZWZnaGlqc3R1dnd4eXqDhIWGh4iJipKTlJWWl5iZmqKjpKWmp6ipqrKztLW2t7i5usLD xMXGx8jJytLT1NXW19jZ2uHi4+Tl5ufo6erx8vP09fb3+Pn6AQADAQEBAQEBAQEB AQIDBAUGBwgJCgsRAAIBAgQEAwQHBQQEAAECdwABAgMRBAUhMQYSQVEHYXETIjKBCBRCkaGx wQkjM1LwFWJy0QoWJDThJfEXGBkaJicoKSo1Njc4OTpDREVGR0hJSlNUVVZXWFlaY2RlZmdo aWpzdHV2d3h5eoKDhIWGh4iJipKTlJWWl5iZmqKjpKWmp6ipqrKztLW2t7i5usLDxMXGx8jJ ytLT1NXW19jZ2uLj5OXm5+jp6vLz9PX29/j5+v/AABEIAHgAoAMBIQACEQEDEQH/2gAMAwEA AhEDEQA/AMead5GxnJ9KjaPYuTy1YtnQlYqk7ZM1dgl3Lg1b2MzZ02TMZX0qvr97cR2AtIjt idsvjq1EZWkRKPMZ2j2U9xcIqxts/i4rv7SwW2gVFGB1NKb1HcfNEGXBFZstlDz8xBqAM+8Q QoTnIrmtQuQcgGriJk3hqXF1IPUV10T5FWySXNJmkA1z8prjPEHf/eo6jRhir9r0q2NGnDG XqNc5frnPrULMMk/NgdqkMoTB+XjrzVO4uBgDlyfQUpWa2KS7H//2Q== --__CONTENT_64564_PART_BOUNDARY__33243242__-- -- http://mail.python.org/mailman/listinfo/python-list
Re: ImageMagick Issue
I ran into another slight problem. And I attempted to fix it, but have not been able to do so yet. If a filename does not contain a space, then this method works like a charm. But if there is a space then the code throws a nasty error. import os import subprocess from os import * imagefile = /somedir/images/david.huggins/Photo 1.jpg cmdw = identify -format %w '+imagefile+' cmdh = identify -format %h '+imagefile+' pw = subprocess.Popen(cmdw.split(), stdout=subprocess.PIPE, stderr= subprocess.STDOUT) ph = subprocess.Popen(cmdh.split(), stdout=subprocess.PIPE, stderr= subprocess.STDOUT) w = pw.stdout.read().strip() h = ph.stdout.read().strip() identify: Unable to open file ('/somedir/images/david.huggins/Photo) [No such file or directory]. identify: Unable to open file (1.jpg') [No such file or directory]. identify: Missing an image file name [No such file or directory]. identify: Unable to open file ('/somedir/images/david.huggins/Photo) [No such file or directory]. identify: Unable to open file (1.jpg') [No such file or directory]. identify: Missing an image file name [No such file or directory]. Traceback (most recent call last): On 5/31/07, Facundo Batista [EMAIL PROTECTED] wrote: Sick Monkey wrote: When I run the following command: [EMAIL PROTECTED] david.huggins]# identify -format %w '/someDIR/images/david.huggins/100_0264.JPG' From Python interpreter: cmd = identify -format %w test.jpg p = subprocess.Popen(cmd.split(), stdout=subprocess.PIPE, stderr= subprocess.STDOUT) t = p.stdout.read() p.stdout.close() t '50\n' From command line: [EMAIL PROTECTED]:~$ identify -format %w test.jpg 50 [EMAIL PROTECTED]:~$ Regards, -- . Facundo . Blog: http://www.taniquetil.com.ar/plog/ PyAr: http://www.python.org/ar/ -- http://mail.python.org/mailman/listinfo/python-list -- http://mail.python.org/mailman/listinfo/python-list
ImageMagick Issue
I have the following: OS = RedHat ImagMagick installed. Python v2.5 - When I run the following command: [EMAIL PROTECTED] david.huggins]# identify -format %w '/someDIR/images/david.huggins/100_0264.JPG' I get the following result 2304 However, when I try to set this value to a variable, ie w= os.system(identify -format %w '/someDIR/images/david.huggins/100_0264.JPG') print w I get TypeError: argument 1 must be string or read-only buffer, not int NOTE: This is coming from a Python Servlet Page. As always, any input is GREATLY appreciated. Thanks Dave -- http://mail.python.org/mailman/listinfo/python-list
Re: py2exe compiling
Have you looked at the Tips and Tricks on Py2exe's website? http://www.py2exe.org/index.cgi/GeneralTipsAndTricks I believe this next link will help you add custom data to your app. http://www.py2exe.org/index.cgi/CustomDataInExe .dave On 5/21/07, Pyro [EMAIL PROTECTED] wrote: Hello, I have just finished my script and am ready to distrabute it. I am having a little trouble using py2exe though. here is what i have at the top of my file for imports: import string, array, sgmllib, re, sys, cookielib, urllib2, random, ConfigParser, time from urllib2 import urlopen from ClientForm import ParseResponse from configobj import ConfigObj Now, there are some other file attributes i need a bit of help with. icon = nigel.ico file name = name file author = cody woolaver file version = 0.1.3 file comments = uhhh, a comment ^^ Thanks for your help ~Cody Woolaver -- http://mail.python.org/mailman/listinfo/python-list -- http://mail.python.org/mailman/listinfo/python-list
interesting dict bug
Here is a segment of some code that I have. CODE: -- print filename params2 = {'filename':filename,'id3title':title,'id3artist':artist,'id3album':album,'id3year':year,'id3track':track,'id3genre':genre,'uname':username,'password':password,'filesToUpload':open(file, 'rb')} print params2 OUTPUT: 01.mp3 {'password': u'XXX', 'id3year': '2002', 'id3album': 'album, 'id3title': 'Lose Yourself', 'filename': u'01.mp3', 'uname': u'', 'id3genre': 'Soundtrack', 'id3artist': 'Eminem', 'filesToUpload': open file u'/Users/ozdon/Music/test2/01-eminemhhh.mp3', mode 'rb' at 0x106a5c0, 'id3track': 'Unknown'} -- Does anyone know how the random u' is getting into the params2 or know how to around this? I am using Python 2.5 on MacOSX. -- http://mail.python.org/mailman/listinfo/python-list
Re: interesting dict bug
Ahhh thank you so much! I just added a .encode('utf-8') to the variables causing problems and that resolved my issue. Much appreciated! .dave On 5/19/07, Jeff McNeil [EMAIL PROTECTED] wrote: Filename is a unicode string. See http://www.diveintopython.org/xml_processing/unicode.html or http://docs.python.org/tut/node5.html#SECTION00513. Python 2.5 (r25:51918, Sep 19 2006, 08:49:13) [GCC 4.0.1 (Apple Computer, Inc. build 5341)] on darwin Type help, copyright, credits or license for more information. s = string unicode(s) u'string' You're not seeing the 'u' in the 'print filename' line as it isn't actually part of the data. You will see it in the 'print params2' output, though, as I believe it relies on the string object's __repr__ function, which will include the unicode specifier. -Jeff On 5/19/07, Sick Monkey [EMAIL PROTECTED] wrote: Here is a segment of some code that I have. CODE: -- print filename params2 = {'filename':filename,'id3title':title,'id3artist':artist,'id3album':album,'id3year':year,'id3track':track,'id3genre':genre,'uname':username,'password':password,'filesToUpload':open(file, 'rb')} print params2 OUTPUT: 01.mp3 {'password': u'XXX', 'id3year': '2002', 'id3album': 'album, 'id3title': 'Lose Yourself', 'filename': u'01.mp3', 'uname': u'', 'id3genre': 'Soundtrack', 'id3artist': 'Eminem', 'filesToUpload': open file u'/Users/ozdon/Music/test2/01- eminemhhh.mp3', mode 'rb' at 0x106a5c0, 'id3track': 'Unknown'} -- Does anyone know how the random u' is getting into the params2 or know how to around this? I am using Python 2.5 on MacOSX. -- http://mail.python.org/mailman/listinfo/python-list -- http://mail.python.org/mailman/listinfo/python-list
wxpython - button question
I have the following code which will basically take an image file and create a bitmap image. I am having one problem though in that there is a white border around the image. Does anyone know how to take that off? imageFile2 = image.png image2 = wx.Image(imageFile2, wx.BITMAP_TYPE_ANY).ConvertToBitmap() self.button2 = wx.BitmapButton(self, id=-1, bitmap=image2, pos=(10, 140), size = (image2.GetWidth()-2, image2.GetHeight())) self.button2.SetMargins(0,0) self.button2.Bind(wx.EVT_BUTTON, self.button2Click) -- http://mail.python.org/mailman/listinfo/python-list
Re: file uploader
I never heard a response back concerning my previous question, so I decided to write my own function. If anyone has a simpler way of checking to see if a file already exists (prior to uploading to a server) and renaming it, please let me know. Here is the code that I am using (it runs exactly the same as the linux app 'arcgen'). % import os,string filename = whoa.mp3 dir_path = /u01/ i = 0 while os.path.exists(dir_path+filename): #filename=string.replace(filename, .-0,.-1) if i == 0: filename = %s.-%s % (filename,i) else: t = i-1 filename=string.replace(filename,.-%s % (t),.-%s % (i)) i += 1 req.write(filename) % The directory contains the following files: whoa.mp3 and whoa.mp3.-0. This code will output whoa.mp3.-1. On 5/9/07, Sick Monkey [EMAIL PROTECTED] wrote: Hey guys. I wanted to write a little desktop application that would upload files to an external server, to a specific directory. The desktop application is running on Mac OS X and I built a .psp script that is running on a Red Hat server. NOTE: This application is written for Python 2.5 (both py and psp) My code is giving me problems, in that it is overwriting files. I was wondering if anyone knew of a module or a method that would overcome this dilemma. I can adapt my program to search to see if the file existed already in the directory and append a random string sequence to keep this from occurring, but I do not want to reinvent the wheel (if such a thing exists) and that would clutter up my program. :) Here is what I am currently using: fname = os.path.basename(uploadFile.filename) dir_path = /u01 open(os.path.join(dir_path, fname), 'wb').write(uploadFile.file.read()) As always, any help is greatly appreciated. .dave -- http://mail.python.org/mailman/listinfo/python-list
Re: append
http://docs.python.org/tut/node7.html Yes there is a pop function. An example that uses most of the list methods: a = [66.25, 333, 333, 1, 1234.5] print a.count(333), a.count(66.25), a.count('x') 2 1 0 a.insert(2, -1) a.append(333) a [66.25, 333, -1, 333, 1, 1234.5, 333] a.index(333) 1 a.remove(333) a [66.25, -1, 333, 1, 1234.5, 333] a.reverse() a [333, 1234.5, 1, 333, -1, 66.25] a.sort() a [-1, 1, 66.25, 333, 333, 1234.5] On 10 May 2007 10:02:26 -0700, HMS Surprise [EMAIL PROTECTED] wrote: Trying not to be a whiner but I sure have trouble finding syntax in the reference material. I want to know about list operations such as append. Is there a pop type function? I looked in tutorial, language reference, and lib for list, append, sequence. Is there a place where us doofi ( who may not have our heads out in the sunlight) may find all related syntax grouped together? thanx, jh -- http://mail.python.org/mailman/listinfo/python-list -- http://mail.python.org/mailman/listinfo/python-list
file uploader
Hey guys. I wanted to write a little desktop application that would upload files to an external server, to a specific directory. The desktop application is running on Mac OS X and I built a .psp script that is running on a Red Hat server. NOTE: This application is written for Python 2.5 (both py and psp) My code is giving me problems, in that it is overwriting files. I was wondering if anyone knew of a module or a method that would overcome this dilemma. I can adapt my program to search to see if the file existed already in the directory and append a random string sequence to keep this from occurring, but I do not want to reinvent the wheel (if such a thing exists) and that would clutter up my program. :) Here is what I am currently using: fname = os.path.basename(uploadFile.filename) dir_path = /u01 open(os.path.join(dir_path, fname), 'wb').write(uploadFile.file.read()) As always, any help is greatly appreciated. .dave -- http://mail.python.org/mailman/listinfo/python-list
Re: recursively removing files and directories
Here is some code that could be useful It does not check the directories for 0 files, but that shouldn't be too difficult to add. # from os import listdir, unlink from os.path import isdir, isfile, islink, join, getmtime deldir = C:\Some\Dir delFileType = .txt# or You could use Regex. # - def del_entry(_name): try: if isdir(_name): print Do Nothing else: #print now unlink(_name) # or remove(_name) sys.stdout.write(Delete FILE %s\n % (_name)) except IOError: sys.stderr.write(Cannot delete %s\n % (_name)) # - def list_dir(_dir,_action): if not isdir(_dir): print %s is not a directory % (_dir) return for file in listdir(_dir): path = join(_dir, file) if isdir(path): list_dir(path, _action) else: # isfile() or islink() if path.rfind(delFileType) != -1: #print path _action(path) # Run it list_dir(deldir, del_entry) # On 9 Apr 2007 11:44:10 -0700, bahoo [EMAIL PROTECTED] wrote: Hi, I found a message on Jan 16, 2006 regarding the same topic, except that I wanted to remove only certain files that satisfy the format ABC_XXX_XXX.dat, but not the other files. Once the files are removed, if a folder becomes empty, I want to remove the folder as well. The solution to the Jan 16 2006 message required many lines of python code. I was wondering if there is a simpler solution to my problem at hand, perhaps by using more specialized functions? Thanks! bahoo -- http://mail.python.org/mailman/listinfo/python-list -- http://mail.python.org/mailman/listinfo/python-list
Re: Looping issues
Try this. NOTE: The script below will compare lines of both files (even hidden characters such as \n)... def fopen(fname): try: return open(fname, 'U') except IOError, detail: return fail(couldn't open + fname + : + str(detail)) f1 = fopen('file1.txt') a = f1.readlines(); f1.close() d1 = {} for c in a: d1[c.lower()] = None #print d1 f2 = fopen('file2.txt') data = f2.readlines(); f2.close() for line in data: if d1.has_key( line ): print line wdh On 5 Apr 2007 11:01:09 -0700, [EMAIL PROTECTED] [EMAIL PROTECTED] wrote: What I am trying to do is compare two files to each other. If the 2nd file contains the same line the first file contains, I want to print it. I wrote up the following code: correct_settings = open(C:\Python25\Scripts\Output \correct_settings.txt,r) current_settings = open(C:\Python25\Scripts\Output\output.txt,r) for line in correct_settings: for val in current_settings: if val == line: print line + found. correct_settings.close() current_settings.close() For some reason this only looks at the first line of the correct_settings.txt file. Any ideas as to how i can loop through each line of the correct_settings file instead of just looking at the first? -- http://mail.python.org/mailman/listinfo/python-list -- http://mail.python.org/mailman/listinfo/python-list
Re: Looping issues
Ooops, Sorry I left .lower() out. def fopen(fname): try: return open(fname, 'U') except IOError, detail: return fail(couldn't open + fname + : + str(detail)) f1 = fopen('file1.txt') a = f1.readlines(); f1.close() d1 = {} for c in a: d1[c.lower()] = None #print d1 f2 = fopen('file2.txt') data = f2.readlines(); f2.close() for line in data: if d1.has_key( line.lower() ): print line On 4/5/07, Sick Monkey [EMAIL PROTECTED] wrote: Try this. NOTE: The script below will compare lines of both files (even hidden characters such as \n)... def fopen(fname): try: return open(fname, 'U') except IOError, detail: return fail(couldn't open + fname + : + str(detail)) f1 = fopen('file1.txt ') a = f1.readlines(); f1.close() d1 = {} for c in a: d1[c.lower()] = None #print d1 f2 = fopen('file2.txt') data = f2.readlines(); f2.close() for line in data: if d1.has_key( line ): print line wdh On 5 Apr 2007 11:01:09 -0700, [EMAIL PROTECTED] [EMAIL PROTECTED] wrote: What I am trying to do is compare two files to each other. If the 2nd file contains the same line the first file contains, I want to print it. I wrote up the following code: correct_settings = open(C:\Python25\Scripts\Output \correct_settings.txt,r) current_settings = open(C:\Python25\Scripts\Output\output.txt,r) for line in correct_settings: for val in current_settings: if val == line: print line + found. correct_settings.close() current_settings.close() For some reason this only looks at the first line of the correct_settings.txt file. Any ideas as to how i can loop through each line of the correct_settings file instead of just looking at the first? -- http://mail.python.org/mailman/listinfo/python-list -- http://mail.python.org/mailman/listinfo/python-list
Re: Cascading ifs
If it is just the indentation that is bothering you, you could do this: match = test if match == 1: print 1 elif match == 2: print 2 elif match == test: print test On 4/2/07, Ernesto García García [EMAIL PROTECTED] wrote: Hi experts, How would you do this without the more and more indenting cascade of ifs?: match = my_regex.search(line) if match: doSomething(line) else: match = my_regex2.search(line) if match: doSomething2(line) else: match = my_regex3.search(line) if match: doSomething3(line) etc. Thanks in advance and regards, Ernesto -- http://mail.python.org/mailman/listinfo/python-list -- http://mail.python.org/mailman/listinfo/python-list
Re: Python shell on mac os x
I use iTerm and it took me a while to get use to it as well. All you have to do is go to Bookmarks- Manage Profiles Then expand Terminal Profiles -Default and then for type select linux. You may have to restart iTerm, but you will be able to do everything you can in linux. Let me know if that does not help and I will look further. Take care. .dave huggins aka sicksickmonkey On 3/15/07, Greg Donald [EMAIL PROTECTED] wrote: On 15 Mar 2007 14:56:13 -0700, Bert Heymans [EMAIL PROTECTED] wrote: ^[OA^[OC^[OD Is your python built with readline support? Also, you might check out iPython. -- Greg Donald http://destiney.com/ -- http://mail.python.org/mailman/listinfo/python-list -- http://mail.python.org/mailman/listinfo/python-list
Re: Python Eggs on Cygwin
Just by looking at the permission denied error, when you loaded the MySQLdb module, were you using a specific user (is it owned by a specific user)? On 15 Mar 2007 17:33:29 -0700, [EMAIL PROTECTED] [EMAIL PROTECTED] wrote: Hi, I'm trying to use MySQL Python module on Cygwin. Since there is no binary package, I compiled MySQL C client library and Python module (http://sourceforge.net/projects/mysql-python) manually. But when I was trying to load MySQLdb module, following errors happened. import MySQLdb Traceback (most recent call last): File stdin, line 1, in ? File build/bdist.cygwin-1.5.22-i686/egg/MySQLdb/__init__.py, line 19, in ? File build/bdist.cygwin-1.5.22-i686/egg/_mysql.py, line 7, in ? File build/bdist.cygwin-1.5.22-i686/egg/_mysql.py, line 6, in __bootstrap__ ImportError: Permission denied This seems to be Eggs/Cygwin problem. Is there any solution? Regards, -- Kazu Nisimura -- http://mail.python.org/mailman/listinfo/python-list -- http://mail.python.org/mailman/listinfo/python-list
Re: Readline()
Maybe if you show us your code we can better assist you. But maybe you can use a global variable or a try-catch method to keep threads from staying alive and help better control your code. On 3/12/07, Taylor, Stuart [EMAIL PROTECTED] wrote: I have been working on running an external process using subprocess.popenfor a few days. The process is ran over the network to another machine. One thing I have found is that if I perform readline() on the stdout it will hang if the process loses connection. I have tried a few things in a test example: one is to use stdin.writethen stdin.flush() which send a string that readline() will read and it ends correctly but doesn't work on the project I need it to work on. Another is to try using threads and ignoar the thread when the process has lost connection but this still leaves the open thread alive even when the main app has finished. I am relatively new to python and I may be making a fundemantal mistake in my implementation, can anyone please inform me of whether sticking with subprocess.popen and readline() is the correct procedure for this sort of task? And if anyone can point me in the correct implementation of this problem I would be gratefull. Thank you Stuart -- http://mail.python.org/mailman/listinfo/python-list -- http://mail.python.org/mailman/listinfo/python-list
Re: making an executable for a python code (newbie)
You will probably want to read this documentation: http://pyinstaller.hpcf.upr.edu/docs/Manual_v1.1.html Look carefully at the following sections on the documentation: Building the runtime environment and Spec File and Spec File - EXE http://pyinstaller.hpcf.upr.edu/docs/Manual_v1.1.html#id4On 3/10/07, Pradnyesh Sawant [EMAIL PROTECTED] wrote: hello, i have some python scripts (especially, PyQt4 scripts) that i want to deploy on both linux and windows m/c's. different packaging tools that i checked (cx_freeze, distutils, pyinstaller) allow me to create installers. however, i'm interested in creating executables that allow the code to be run just on double clicking. is there any way to get this done? also, it seems that pyexe creates a windows executable, but how do i use it on linux? thanks for all the help! -- http://mail.python.org/mailman/listinfo/python-list -- http://mail.python.org/mailman/listinfo/python-list
Re: SQLAlchemy and Oracle Functions?
Helpful Links http://sourceforge.net/projects/cx-oracle http://www.python.net/crew/atuining/cx_Oracle/html/cursorobj.html == Example: Replace the data types as appropriate. v_Vars = v_Cursor.setinputsizes(p_Result = cx_Oracle.NUMBER) v_Cursor.execute( begin :p_Result := sch.pkg.myfunction(:p_Param1, :p_Param2, :p_Param3); end;, p_Param1 = 1, p_Param2 = Some string, p_Param3 = A different string) print Result:, v_Vars[p_Result].getvalue() On 8 Mar 2007 13:11:00 -0800, Greg Copeland [EMAIL PROTECTED] wrote: I have a need to call an Oracle function, which is not the same thing as a stored procedure. Can SQLAlchemy do this directly? Indirectly? If so, an example would be appreciated. If not, how do I obtain the raw cx_Oracle cursor so I can use that directly? Thanks, Greg -- http://mail.python.org/mailman/listinfo/python-list -- http://mail.python.org/mailman/listinfo/python-list
Re: What is the best way to upgrade python?
Have you tried to upgrade the current python RPM? rpm -Uvh You can also build from source. Once you get Python 2.4 up and running I am pretty sure you can do a symbolic link on the python 2.3 application (either in /usr/bin or /usr/sbin) and point it to the 2.4 python file. On 8 Mar 2007 13:13:13 -0800, [EMAIL PROTECTED] [EMAIL PROTECTED] wrote: Hi, i am using red hat enterprise 4. It has python 2.3 installed. What is the best way to upgrade to python 2.4? I think one way is to compile python 2.4 from the source, but I can't remove the old one since when i do 'rpm -e python', i get error like 'failed dependencies'. Thank you for any idea. -- http://mail.python.org/mailman/listinfo/python-list -- http://mail.python.org/mailman/listinfo/python-list
Re: What is the best way to upgrade python?
Yeah, sorry I should have added more data. You will need to go to rhn.redhat.com and either download the RPM or get the url. So you would do: (1) download the rpm to your home directory rpm -Uvh nameOfRPM or (2) grab the url rpm -Uvh http://urlOfRPM either way should update your python. Dont be distressed if you need to update or install new RPMs. On 3/8/07, ying lcs [EMAIL PROTECTED] wrote: On 3/8/07, Sick Monkey [EMAIL PROTECTED] wrote: Have you tried to upgrade the current python RPM? rpm -Uvh You can also build from source. Once you get Python 2.4 up and running I am pretty sure you can do a symbolic link on the python 2.3 application (either in /usr/bin or /usr/sbin) and point it to the 2.4 python file. I get '$rpm -Uvh python' error: open of python failed: no such file or directory but when I do '$rpm -q python ' , I get python -2.3.4-14.1 On 8 Mar 2007 13:13:13 -0800, [EMAIL PROTECTED] [EMAIL PROTECTED] wrote: Hi, i am using red hat enterprise 4. It has python 2.3 installed. What is the best way to upgrade to python 2.4? I think one way is to compile python 2.4 from the source, but I can't remove the old one since when i do 'rpm -e python', i get error like 'failed dependencies'. Thank you for any idea. -- http://mail.python.org/mailman/listinfo/python-list -- http://mail.python.org/mailman/listinfo/python-list
Re: py2exe: LoadLibrary(pythondll) failed
(1) You may want to read the following links: http://docs.python.org/dist/describing-extensions.html#SECTION00234 which came from: http://docs.python.org/dist/dist.html Here is another good resource for py2exe: http://www.py2exe.org/index.cgi/GeneralTipsAndTricks (2) Also, you maybe interested in PyInstaller which can wrap up everything in one functioning exe. http://pyinstaller.python-hosting.com/ Single file: build a single executable file, totally self-contained, which runs without any external dependency. On 3 Mar 2007 10:37:19 -0800, zxo102 [EMAIL PROTECTED] wrote: Hi there, I py2exe my test.py as test.exe with a lot of dll and pyc in that directory. If I move the test.exe into another directory and run it from there, it gives me an error LoadLibrary(pythondll) failed... python24.dll. How can I set it up correctly for this test.exe to run? Thanks. Ouyang -- http://mail.python.org/mailman/listinfo/python-list -- http://mail.python.org/mailman/listinfo/python-list
Python win32 tools
I am trying to build a python program that will reset a user's account (password) on a windows machine (NOTE: my intention here is not to implement anything malicious {and I know about Trinity which is very useful}, but I just wanted a challenge and do it myself.). I have been working with win32 objects and was wondering if this functionality was already built in. Thanks. -- http://mail.python.org/mailman/listinfo/python-list
Re: Py2EXE problem
Ok I found an extremely easy way to resolving this issue (I cannot believe I did not think of it sooner). After Py2exe created the .exe file I noticed a library.zip file. I took a look at the Py2exe output, and saw all of the libraries that it failed to insert. I copied all of the .pyc that my application needed and inserted them in the email folder within the library.zip. I fired up the application and it worked like a champ. On 2/27/07, Sick Monkey [EMAIL PROTECTED] wrote: Maybe this is not the board to post this, but hopefully with all of the python experts out there maybe one of you have encountered this. I wrote an application that sends an email with an attachment. When I run it, it runs great with no issues what-so--ever. When I thought I was finally finished, I created an executable file using py2exe. Now, when I run the application, I am getting the following error: --- Exception in Tkinter callback Traceback (most recent call last): File Tkinter.pyc, line 1403, in __call__ File Suppression.py, line 401, in startProc File Suppression.py , line 318, in emailInfo File email\__init__.pyc, line 79, in __getattr__ ImportError: No module named multipart --- Any ideas on how to get around this one? -- http://mail.python.org/mailman/listinfo/python-list
Re: Py2EXE problem
Awesome. That is good to know. On 2/28/07, Thomas Heller [EMAIL PROTECTED] wrote: Sick Monkey schrieb: Ok I found an extremely easy way to resolving this issue (I cannot believe I did not think of it sooner). After Py2exe created the .exe file I noticed a library.zip file. I took a look at the Py2exe output, and saw all of the libraries that it failed to insert. I copied all of the .pyc that my application needed and inserted them in the email folder within the library.zip. I fired up the application and it worked like a champ. Even easier would be to let py2exe include the whole email package. One solution is to run 'setup.py py2exe -p email' Thomas -- http://mail.python.org/mailman/listinfo/python-list -- http://mail.python.org/mailman/listinfo/python-list
Re: How to check for remaining hard drive space in Windows?
Here you are: from win32com.client import GetObject wmiObj = GetObject(winmgmts:MGW01641\\root\\cimv2) diskinfo = wmiObj.ExecQuery(Select * from Win32_LogicalDisk) for disk in diskinfo: ...print disk.Name, disk.FreeSpace ... A: None C: 16978259968 D: None On 28 Feb 2007 12:26:31 -0800, [EMAIL PROTECTED] [EMAIL PROTECTED] wrote: HI, I am new to Python and wanted to know how to check for the remaining disk space on my Windows machine using Python? I was thinking of using the command line dir and trying to extract the output from there. But I'm not sure how to extract command line strings using Python either. Anyway help would be appreciated. :) -- http://mail.python.org/mailman/listinfo/python-list -- http://mail.python.org/mailman/listinfo/python-list
Re: How to check for remaining hard drive space in Windows?
Sorry, I forgot to make a change. You will need to change COMPUTER_NAME ~~~ from win32com.client import GetObject wmiObj = GetObject(winmgmts:COMPUTER_NAME\\root\\cimv2) diskinfo = wmiObj.ExecQuery(Select * from Win32_LogicalDisk) for disk in diskinfo: ...print disk.Name, disk.FreeSpace On 28 Feb 2007 12:26:31 -0800, [EMAIL PROTECTED] [EMAIL PROTECTED] wrote: HI, I am new to Python and wanted to know how to check for the remaining disk space on my Windows machine using Python? I was thinking of using the command line dir and trying to extract the output from there. But I'm not sure how to extract command line strings using Python either. Anyway help would be appreciated. :) -- http://mail.python.org/mailman/listinfo/python-list -- http://mail.python.org/mailman/listinfo/python-list
Re: text wrapping help
I am not certain if I understand your problem, but I think you are just trying to read in a string and create a visable matrix. If that is true, then may some of the code below will work. This is in no way elegant. ++ count = 1 width = 2 #the width of your matrix string=aa#input string to piece up final= #output string for character in string: if count == width : final = %s%s\n % (final,character) count = 1 else: final = %s%s % (final,character) count += 1 print final On 28 Feb 2007 16:06:08 -0800, Ryan K [EMAIL PROTECTED] wrote: I'm trying to text wrap a string but not using the textwrap module. I have 24x9 matrix and the string needs to be text wrapped according to those dimensions. Is there a known algorithm for this? Maybe some kind of regular expression? I'm having difficulty programming the algorithm. Thanks, Ryan -- http://mail.python.org/mailman/listinfo/python-list -- http://mail.python.org/mailman/listinfo/python-list
Re: pyHook or SetWindowsHookEx
I have just gotten into pyHook, so I could be incredibly wrong, but I have researched a lot into your problem. (cuz I have the same question) I think the python program has to be on the remote machine becuase from my understanding pyHook just reads in the windows' keyboard driver. And when you remote desktop or VNC into another machine, i am pretty sure either windows (for remote desktop) and vnc (the actual host program) controls the key commands so the win objects would not work for remoting. On 28 Feb 2007 09:46:20 -0800, abcd [EMAIL PROTECTED] wrote: anyone? -- http://mail.python.org/mailman/listinfo/python-list -- http://mail.python.org/mailman/listinfo/python-list
Re: os.system and quoted strings
Do you mean: import time, os dir = C:\\Documents and Settings\\somepath\\ fileName = time.strftime(%d%m%Y) finalname = %s%s.txt % (dir,fileName) print finalname C:\Documents and Settings\somepath\27022007.txt On 27 Feb 2007 06:24:41 -0800, svata [EMAIL PROTECTED] wrote: Hello, as I'm new to python I've stumbled accros os.system and its not very well documented usage. I use Win XP Pro and Python 2.5. Here is the code snippet: -- import time import os dir = C:\\Documents and Settings\\somepath\\ fileName = time.strftime(%d%m%Y) os.system('gvim dir+fileName+.txt') --- The problem is that concatenated variable dir+fileName doesn't get expanded as expected. Is there anything I omitted? svata -- http://mail.python.org/mailman/listinfo/python-list -- http://mail.python.org/mailman/listinfo/python-list
Re: book for a starter
I personally would get Programming Python, Third Edition http://www.oreilly.com/catalog/python3/ On 2/27/07, Wensui Liu [EMAIL PROTECTED] wrote: Good morning, all, I just start learning python and have a question regarding books for a newbie like me. If you are only allowed to buy 1 python book, which one will you pick? ^_^. Thank you so much! -- http://mail.python.org/mailman/listinfo/python-list -- http://mail.python.org/mailman/listinfo/python-list
Special Characters
I have a quick question about handling values with special characters. Lets say I have a file which contains: == blah#blah == Here is what I have for my code: f6 = open(fileAttached) msInfo = f6.readlines(); f6.close() varName = msInfo[0] smtp.login(uname,varName) ... == I am trying to connect to a mailserver, and it keeps failing. My guess is that the # sign messing up. Is there anyway to encode that character? -- http://mail.python.org/mailman/listinfo/python-list
Re: Special Characters
Sorry guys. It has been a long day today. There is no issues when dealing with # in variables. I found out that when I was reading the file, there were additional blank spaces being appended to the value. To correct the issue, I just had to dp varName = msInfo[0].strip() finName = varName.strip() On 2/27/07, Sick Monkey [EMAIL PROTECTED] wrote: I have a quick question about handling values with special characters. Lets say I have a file which contains: == blah#blah == Here is what I have for my code: f6 = open(fileAttached) msInfo = f6.readlines(); f6.close() varName = msInfo[0] smtp.login(uname,varName) ... == I am trying to connect to a mailserver, and it keeps failing. My guess is that the # sign messing up. Is there anyway to encode that character? -- http://mail.python.org/mailman/listinfo/python-list
Py2EXE problem
Maybe this is not the board to post this, but hopefully with all of the python experts out there maybe one of you have encountered this. I wrote an application that sends an email with an attachment. When I run it, it runs great with no issues what-so--ever. When I thought I was finally finished, I created an executable file using py2exe. Now, when I run the application, I am getting the following error: --- Exception in Tkinter callback Traceback (most recent call last): File Tkinter.pyc, line 1403, in __call__ File Suppression.py, line 401, in startProc File Suppression.py, line 318, in emailInfo File email\__init__.pyc, line 79, in __getattr__ ImportError: No module named multipart --- Any ideas on how to get around this one? -- http://mail.python.org/mailman/listinfo/python-list
Re: getting info on remote files
You should use os.popen() instead of os.system. os.popen() will return a file-like object that is connected to the stdout of the system command; you can then use that object's read()/readlines() method(s) to assign that output to a Python variable. http://docs.python.org/lib/module-popen2.html On 26 Feb 2007 12:54:39 -0800, [EMAIL PROTECTED] [EMAIL PROTECTED] wrote: hello everyone, Im trying to write some python code that will return information (file size, last modified ...) about files on a remote computer that I have 'no password' ssh access to. Ive been able to write code that logs on to remote computers and I can issue a command using, os.system(ssh blah.blah.blah.org ls -l myfile) but how do I store the information returned by the ls command into a variable. The primary goal of this is to 1. check file size on remote computer 2. scp file to local computer 3. make sure file size of copy and original are the same any suggestions would be appreciated thanks gabe -- http://mail.python.org/mailman/listinfo/python-list -- http://mail.python.org/mailman/listinfo/python-list
Re: Walk thru each subdirectory from a top directory
I had a do something similar. I had to get a program to traverse through a directory and delete all files with a specific file extension. (The program below will delete files, so I do not recommend you running it without paying close attention to it.) This program will start at a given directory and will traverse thru the subdirectories by using listdir. +++ #!/usr/bin/python -u import sys, time from os import listdir, unlink from os.path import isdir, isfile, islink, join, getmtime deldir = C:\some\Dir delFileType = .txt # - def del_entry(_name): try: if isdir(_name): print This is a directory, do nothing. else: #print now unlink(_name) # or remove(_name) sys.stdout.write(Delete FILE %s\n % (_name)) except IOError: sys.stderr.write(Cannot delete %s\n % (_name)) # - def list_dir(_dir,_action): if not isdir(_dir): print %s is not a directory % (_dir) return for file in listdir(_dir): path = join(_dir, file) if isdir(path): list_dir(path, _action) else: if path.rfind(delFileType) != -1: #print path _action(path) # - # Run it list_dir(deldir, del_entry) On 26 Feb 2007 13:28:20 -0800, [EMAIL PROTECTED] [EMAIL PROTECTED] wrote: i am trying to use python to walk thru each subdirectory from a top directory. Here is my script: savedPagesDirectory = /home/meryl/saved_pages/data dir=open(savedPagesDirectory, 'r') for file in dir: if (isdir(file)): # get the full path of the file fileName = savedPagesDirectory + file + 'index.html' print fileName $ ./scripts/regressionTest.py Traceback (most recent call last): File ./scripts/regressionTest.py, line 12, in ? dir=open(savedPagesDirectory, 'r') IOError: [Errno 21] Is a directory But I get the above error: Can you please tell me what did I do wrong? Thank you. -- http://mail.python.org/mailman/listinfo/python-list -- http://mail.python.org/mailman/listinfo/python-list
Re: Python Threads
, You must upload host email list. ) method = 'failed' print ERROR! You need to upload host email address elif f2name =='' and f3name == '': tkMessageBox.showerror ( Open file, You must upload another document to compare host list. ) method = 'failed' print ERROR! You need to upload another file else: thread.start_new_thread(fetchFiles, (f1name,f2name,f3name,)) global threadStat while threadStat == 0: pass ### def openMax(): a = tkFileDialog.askopenfilename() listName[0] = a def openEmail(): b = tkFileDialog.askopenfilename() listName[1] = b def openDomain(): c = tkFileDialog.askopenfilename() listName[2] = c ### main = Tk() bframe = Frame(main) main.title(Suppression Utility) b1 = Button(bframe,text='Host Email List',command=openMax) b2 = Button(bframe,text='Email List',command=openEmail) b3 = Button(bframe,text='Domain List',command=openDomain) b4 = Button(text='Start Processing',command=startProc) bframe.pack(side=TOP) b1.pack(side=LEFT) b3.pack(side=RIGHT) b2.pack(side=RIGHT) b4.pack(side=BOTTOM) main.mainloop() ### Dave Huggins On 2/18/07, Gabriel Genellina [EMAIL PROTECTED] wrote: En Sun, 18 Feb 2007 23:37:02 -0300, Sick Monkey [EMAIL PROTECTED] escribió: Well if this cannot be done, can a thread call a function in the main method? I have been trying and have not been successive. Perhaps I am using thread incorrectly. The safe way to pass information between threads is to use Queue. From inside the working thread, you put() an item with enough state information. On the main (GUI) thread, you use after() to check for any data in the queue, and then update the interfase accordingly. I think there is a recipe in the Python Cookbook http://aspn.activestate.com/ASPN/Cookbook/Python -- Gabriel Genellina -- http://mail.python.org/mailman/listinfo/python-list -- http://mail.python.org/mailman/listinfo/python-list
Re: Regd. converting seconds to hh:mm:ss format
Do you mean epoch time? if so, the below example would work. import time,datetime t = datetime.datetime.now() print t 2007-02-20 13:09:34.851000 print Epoch Seconds:, time.mktime(t.timetuple()) Epoch Seconds: 1171994974.0 # go the other way epochtime = 1171994974 now = datetime.datetime.fromtimestamp(epochtime) print now 2007-02-20 13:09:34 On 2/20/07, Vishal Bhargava [EMAIL PROTECTED] wrote: Is there an inbuilt library in Python which you can use to convert time in seconds to hh:mm:ss format? Thanks, Vishal -- http://mail.python.org/mailman/listinfo/python-list -- http://mail.python.org/mailman/listinfo/python-list
Re: Python Threads
Great, thanks for the tip Gabriel! On 2/18/07, Gabriel Genellina [EMAIL PROTECTED] wrote: En Sun, 18 Feb 2007 23:37:02 -0300, Sick Monkey [EMAIL PROTECTED] escribió: Well if this cannot be done, can a thread call a function in the main method? I have been trying and have not been successive. Perhaps I am using thread incorrectly. The safe way to pass information between threads is to use Queue. From inside the working thread, you put() an item with enough state information. On the main (GUI) thread, you use after() to check for any data in the queue, and then update the interfase accordingly. I think there is a recipe in the Python Cookbook http://aspn.activestate.com/ASPN/Cookbook/Python -- Gabriel Genellina -- http://mail.python.org/mailman/listinfo/python-list -- http://mail.python.org/mailman/listinfo/python-list
Python Threads
Is there anyway to get 2 python threads to talk to one another? I have a GUI which is spawning a thread to make a large calculation (that way the GUI does not appear to be non responsive). I am trying to attach a progress bar to the threaded action. As the thread is calculating data, I would like it to communicate with the other (progress) thread to update it. On windows, when I spawn the progress bar without using threads, the progress bar stalls this does not happen on linux. So I thought by spawning the progress bar by using a thread, it would not stall... If anyone can think of another technique I am all ears. ~~START SAMPLE def progressBar(status): mroot = Tkinter.Tk(className='Worker Bee') metric = Meter(mroot, relief='ridge', bd=3) metric.pack(fill='x') metric.set(status, 'Starting ...') def fetchFiles(file1,file2,file3): method = '' print file1 print file2 print file3 f1 = fopen(file1) a = f1.readlines(); f1.close() d1 = {} for c in a: for m in mailsrch.findall(c): d1[m.lower()] = None I Would like to Update the progress bar running in the other thread here. ## set status = .33 and update progress bar. if file2 == '': domain(d1,file3) #... def startProc(): status = 0 thread.start_new_thread(fetchFiles, (f1name,f2name,f3name,)) thread.start_new_thread(progressBar, (status,)) ~~END SAMPLE -- http://mail.python.org/mailman/listinfo/python-list
Re: Python Threads
Well if this cannot be done, can a thread call a function in the main method? I have been trying and have not been successive. Perhaps I am using thread incorrectly. On 2/18/07, Sick Monkey [EMAIL PROTECTED] wrote: Is there anyway to get 2 python threads to talk to one another? I have a GUI which is spawning a thread to make a large calculation (that way the GUI does not appear to be non responsive). I am trying to attach a progress bar to the threaded action. As the thread is calculating data, I would like it to communicate with the other (progress) thread to update it. On windows, when I spawn the progress bar without using threads, the progress bar stalls this does not happen on linux. So I thought by spawning the progress bar by using a thread, it would not stall... If anyone can think of another technique I am all ears. ~~START SAMPLE def progressBar(status): mroot = Tkinter.Tk(className='Worker Bee') metric = Meter(mroot, relief='ridge', bd=3) metric.pack(fill='x') metric.set(status, 'Starting ...') def fetchFiles(file1,file2,file3): method = '' print file1 print file2 print file3 f1 = fopen(file1) a = f1.readlines(); f1.close() d1 = {} for c in a: for m in mailsrch.findall(c): d1[m.lower()] = None I Would like to Update the progress bar running in the other thread here. ## set status = .33 and update progress bar. if file2 == '': domain(d1,file3) #... def startProc(): status = 0 thread.start_new_thread(fetchFiles, (f1name,f2name,f3name,)) thread.start_new_thread(progressBar, (status,)) ~~END SAMPLE -- http://mail.python.org/mailman/listinfo/python-list
Another Dictionary Question
Hello All. I have a question concerning searching data within dictionaries. Lets say I have a dictionary called db. db = {'[EMAIL PROTECTED]':'none', '[EMAIL PROTECTED]':'none', '[EMAIL PROTECTED]':'none', '[EMAIL PROTECTED]':'none',} And I want to pull out all of the gmail.com addresses.. How would I do this? NOTE: I already have a regular expression to search for this, but I feel that looping over a dictionary is not very efficient. So I have: domsrch = re.compile(r@(\S+)) listToLookFor = ['gmail.com'] db = {'[EMAIL PROTECTED]':'none', '[EMAIL PROTECTED]':'none', '[EMAIL PROTECTED]':'none', '[EMAIL PROTECTED]':'none',} I wonder if there is a way to do something like Psuedo code for item in listToLookFor: if domsrch.findall(db.has_key( item )): print horray NOTE: I know the findall is for lists, but I dont know of an efficient way to search for this in a dictionary. Thanks in advance. -- http://mail.python.org/mailman/listinfo/python-list
Dictionary/Hash question
Even though I am starting to get the hang of Python, I continue to find myself finding problems that I cannot solve. I have never used dictionaries before and I feel that they really help improve efficiency when trying to analyze huge amounts of data (rather than having nested loops). Basically what I have is 2 different files containing data. My program will take the first line in one file and see if it exists in another file. If it does find a match, then it will write the data to a file. --- Right now, the code will open file1 and store all contents in a list. Then it will do the same thing to file2. THN it will loop over list1 and insert into a Hash table. I am trying to find out a way to make this code more efficient. SO here is what i would rather have. when i open file1 send directly to the hash table totally bypassing the insertion of the script.. Is this possible? def fcompare(f1name, f2name): import re mailsrch = re.compile(r'[EMAIL PROTECTED],4}') f1 = fopen(f1name) f2 = fopen(f2name) if not f1 or not f2: return 0 a = f1.readlines(); f1.close() b = f2.readlines(); f2.close() file1List= [] print starting list 1 for c in a: file1List.extend(mailsrch.findall(c)) print storing File1 in dictionary. d1 = {} for item in file1List : d1[item] = None print finished storing information in lists. print starting list 2 file2List = [] for d in b: file2List.extend(mailsrch.findall(d)) utp = open(match.txt,w) for item in file2List : if d1.has_key( item ) : utp.write(item + '\n') utp.close() #del file1List #del file2List print finished comparing 2 lists. #return 1 -- http://mail.python.org/mailman/listinfo/python-list
Re: Dictionary/Hash question
I have never seen this with open(fname,'r') as finput: It is actually throwing an error . Do I have to import a special library to use this? File dictNew.py, line 23 with open(fname,'r') as finput: ^ SyntaxError: invalid syntax On 2/6/07, Gabriel Genellina [EMAIL PROTECTED] wrote: En Tue, 06 Feb 2007 20:31:17 -0300, Sick Monkey [EMAIL PROTECTED] escribió: Even though I am starting to get the hang of Python, I continue to find myself finding problems that I cannot solve. I have never used dictionaries before and I feel that they really help improve efficiency when trying to analyze huge amounts of data (rather than having nested loops). You are right, a list is not the right data structure in your case. But a dictionary is a mapping from keys to values, and you have no values to store. In this case one should use a set: like a list, but without ordering, and no duplicated elements. Also, it's not necesary to read all lines at once, you can process both files line by line. And since reading both files appears to be the same thing, you can make a function: def mailsfromfile(fname): result = set() with open(fname,'r') as finput: for line in finput: mails = some_regular_expression.findall(line) if mails: result.update(mails) return result mails1 = mailsfromfile(f1name) mails2 = mailsfromfile(f2name) for mail in mails1 mails2: # = set intersection, mails present on both files # write mail to output file -- Gabriel Genellina -- http://mail.python.org/mailman/listinfo/python-list -- http://mail.python.org/mailman/listinfo/python-list
Re: Dictionary/Hash question
qualm after qualm. Before you read this, my OS is Linux, up2date, and minimal RAM (512). On purpose becuase I want this app to run on anything. I have 2 very good solutions to this problem (AND I WANT TO THANK 'Gabriel Genellina' AND 'Don Morrison' with comparing 2 LARGE files). (LARGE means anywhere from 2MB to 800MB) The files that my script needs to read in and interpret can contain anywhere from 5 million lines to 65 million lines I have attached 2 versions of code for you to analyze. = I am having issues with performance. Instance 1: dict_compare.py {which is attached} Is awesome, in that I have read a file and stored it into a hash table, but if you run it, the program decides to stall after writing all of the date. NOTE: once you receive the statement finished comparing 2 lists. the file has actually finished processing within 1 minute, but the script continues to run for additional minutes (10 additional minutes actually). I dont know why Instance 2: dictNew.py Runs great but it is a little slower than Instance 1 (dict_compare.py). BUT WHEN IT FINISHES, IT STOPS THE APPLICATION no additional minutes. NOTE: I was not yelling with the capitalization, but I am frustrated Can anyone tell me why Intance1 takes so long to finish? I love both methods, but I cannot understand the timeframe differences. HELP!!! Output Test1: [EMAIL PROTECTED] hash]# date Tue Feb 6 21:23:52 EST 2007 [EMAIL PROTECTED] hash]# python dict_compare.py date starting list 2 finished storing information in lists. storing File1 in dictionary. finished comparing 2 lists. Stopped processing done [EMAIL PROTECTED] hash]# date Tue Feb 6 21:36:14 EST 2007 Total: Over 10 minutes Output Test2: Tue Feb 6 21:38:55 EST 2007 [EMAIL PROTECTED] hash]# python dictNew.py date finished comparing 2 lists. Stopped processing done [EMAIL PROTECTED] hash]# date Tue Feb 6 21:40:36 EST 2007 Total: Less than 2 minutes On 2/6/07, Gabriel Genellina [EMAIL PROTECTED] wrote: En Tue, 06 Feb 2007 22:18:07 -0300, Sick Monkey [EMAIL PROTECTED] escribió: I have never seen this with open(fname,'r') as finput: It is actually throwing an error . Do I have to import a special library to use this? File dictNew.py, line 23 with open(fname,'r') as finput: ^ SyntaxError: invalid syntax Oh, sorry. You need two things: - Python 2.5 - include this line at the very beginning of your script: from __future__ import with_statement If you're using an earlier version, you can write: finput = open(fname,'r') try ... finally finput.close() (Or just omit the try/finally and rely on the garbage collector, but it's not the recommended practice, specially when external resources are involved, like files). -- Gabriel Genellina -- http://mail.python.org/mailman/listinfo/python-list dictNew.py Description: application/python dict_compare.py Description: application/python -- http://mail.python.org/mailman/listinfo/python-list
Re: PYTHONPATH or any other way to set seachpath (winXP) ?
If you need to extend your PATH variable, I have used this in the past. This should not require a reboot. ~~ def AddSysPath(new_path): new_path = os.path.abspath(new_path) do = -1 if os.path.exists(new_path): do = 1 # check against all paths currently available for x in sys.path: x = os.path.abspath(x) if sys.platform == 'win32': x = x.lower() if new_path in (x, x + os.sep): do = 0 # add path if we don't already have it if do: sys.path.append(new_path) pass return do On 2/3/07, Stef Mientki [EMAIL PROTECTED] wrote: Is it possible to change the searchpath for modules on the flight, under winXP ? Most preferred is some command to extend the searchpath. (the environment variable PYTHONPATH needs a reboot) thanks, Stef Mientki -- http://mail.python.org/mailman/listinfo/python-list -- http://mail.python.org/mailman/listinfo/python-list
Re: Diff between opening files in 'r' and 'r+' mode
It was a little hard to follow your logic of your sample code (writing, reading and writing again), but (1)The difference between r and r+. - 'r+' opens the file for both reading and writing. - 'r' should be used when the file will only be read. I am not sure on how you want to store the contents of the file, but I have provided an example below. You could do something like this: -- fileContent = open(fname, 'r') a = fileContent.readlines(); fileContent.close() print a -- (2) If you are just going to read the file, then yes I would use just the 'r' argument. On 30 Jan 2007 01:36:15 -0800, raghu [EMAIL PROTECTED] wrote: i want to know the difference between 'r' mode and 'r+' mode 1.i = open('c:\python25\integer.txt','w')for writiing i.write('hai')-written some content in text file i = open('c:\python25\integer.txt','r')for reading print i.read()for printing the contents in that text file i = open('c:\python25\integer.txt','w')--for writing i.write('how')---?Rewrite the contents print i.read() [MY QUESTION]:i want to read the text file contents cant it be done by giving (print i.read())? Before going to next question [I deleted all the contents in the text file] 2.i = open('c:\python25\integer.txt','r+')-For reading and writing i.write('hai')-written some content to text file print i.read()-{؆('c:\python25\integer.txt','w') i write('') print i.read()how') i = open('c:\python25\integer.txt','r') print i.read() i = open('c:\python25\integer.txt','w') i.write() i = open('c:\python25\integer.txt','r') print i.read() } ---Thats what i saw on interpreter(In curly braces) when i ran the script [MY QUESTION]:1.from where the above in curly braces is printed?and i have written only 'hai' to the text file 2.Should i recall again the opening of the file in 'r' mode to read the file? -- http://mail.python.org/mailman/listinfo/python-list -- http://mail.python.org/mailman/listinfo/python-list
Re: Synchronous shutil.copyfile()
First off, I am just learning Python, so if there is a more efficient way to do this, then I am all ears (NOTE: The code below is something that I was messing with to learn threads... So some functionality is not applicable for your needs..I just wanted to show you a demonstration) One way that you could get around this, is to use threads. You can lock your thread and when the lock has been released, you could open it and ensure your copy has succeeded. Just a thought ~~~ import thread def counter(myId, count): for i in range(count): stdoutmutex.acquire() #Copy Your File Here stdoutmutex.release() exitmutexes[myId].acquire() stdoutmutex = thread.allocate_lock() exitmutexes = [] for i in range(2): exitmutexes.append(thread.allocate_lock()) thread.start_new(counter, (i, 2)) for mutex in exitmutexes: while not mutex.locked(): #Open Your File Here print 'Exiting' On 1/30/07, Hugo Ferreira [EMAIL PROTECTED] wrote: Hi there, I have a problem. I'm using calling shutil.copyfile() followed by open(). The thing is that most of the times open() is called before the actual file is copied. I don't have this problem when doing a step-by-step debug, since I give enough time for the OS to copy the file, but at run-time, it throws an exception. Is there anyway to force a sync copy of the file (make python wait for the completion)? Thanks in advance! Hugo Ferreira -- http://mail.python.org/mailman/listinfo/python-list -- http://mail.python.org/mailman/listinfo/python-list
difflib qualm
I am trying to write a python script that will compare 2 files which contains names (millions of them). More specifically, I have 2 files (Files1.txt and Files2.txt). Files1.txtcontains 180 thousand names and Files2.txt contains 34 million names. I have a script which will analyze these two files and store them into 2 different lists (fileList1 and fileList2 respectivly). I have imported the diflib library and after the lists are created, matching on the following criteria for diflib - (just the names that are similar between the two files). This works perfectly for hundreds of names but is taking forever for millions of them; thus not really efficient. Does anyone have any idea on how to get this more efficient? (speaking of Time and RAM) Any advice would be greatly appreciated. (NOTE: I have been trying to study multithreading, but have not really grasp the concept. So I may need some examples.) ~~ S.C.M. -- http://mail.python.org/mailman/listinfo/python-list
Re: OOPS concept
Google, search. km [EMAIL PROTECTED] ??? news:[EMAIL PROTECTED] ???... Hi all, Well this doesnt explain new style classes. let me be more clear. is there any online tutorial/ recommended book which deals explicitly with object oriented programming in python? regards, KM -- - Try this online book, it may help, the url is: http://www.byteofpython.info Hi all, Is there any good step by step online tutorial on OOPS concepts in python ? i have checked some on the python.org.__doc__ page but couldnt make much sense. especially i need help on newstyle classes. regards, KM -- http://mail.python.org/mailman/listinfo/python-list -- http://mail.python.org/mailman/listinfo/python-list
Re: OOPS concept
Try this online book, it may help, the url is: http://www.byteofpython.info Hi all, Is there any good step by step online tutorial on OOPS concepts in python ? i have checked some on the python.org.__doc__ page but couldnt make much sense. especially i need help on newstyle classes. regards, KM -- http://mail.python.org/mailman/listinfo/python-list
Re: wxpython on cygwin for drPython - ImportError: No module named _core_
I install the original python(www.python.org), it works with wxpython and DrPython very very well. But your case seem to be due to DrPython is not programed for Cygwin. You should read through the system requirement of DrPython. As remember, it stated the www.python.org only ( ; Hi, Did someone installed and used successfully drPython on Cygwin? The installation requires wxpython. I tried many different alternatives (source, binary, etc) but so far the best I get is the following. -- http://mail.python.org/mailman/listinfo/python-list
Re: Is python support jxta now?
Bittorrent, one of the most actively used p2p protocols is _written_ in python. Diez B. Roggisch Hey man, no, the jxta p2p protocols is not mean the bittorrent stuff. It is a fully decentralized network protocol, not confine to file transfer. -- http://mail.python.org/mailman/listinfo/python-list
Re: Comparision of GUI framworks
wxPython rules ( ; Go to http://wxpython.org for details... Florian Lindner [EMAIL PROTECTED] ??? news:[EMAIL PROTECTED] ???... Hello, I've read the chapter in the Python documentation, but I'm interested in a a more in-depth comparision. Especially regarding how pythonic it is and how well it performs and looks under Windows. I've some C++ experiences with Qt, so I'm very interested to have PyQt compared to wxWindows and Tk. How fast does PyQt catches up with the versiones released from Trolltech? etc.. Thx, Florian -- http://mail.python.org/mailman/listinfo/python-list
wxPython: ansi or unicode?
Hi all, which should be install? Really confused @@... Is that mean unicode version used for programming in language other than English? -- http://mail.python.org/mailman/listinfo/python-list
Re: wxPython: ansi or unicode?
Many Thanks ( : Hi all, which should be install? Really confused @@... Unicode. Is that mean unicode version used for programming in language other than English? No. The Unicode version allows the underlying wxWidgets GUI toolkit to use Unicode text. You want this. On certain platforms, older versions of the unicode version of wxPython were somewhat unstable. I believe this has been largely resolved, and the ANSI versions will be going away. I may have some details wrong. If you want an authoritative answer, ask on the wxPython lists. -- Robert Kern [EMAIL PROTECTED] In the fields of hell where the grass grows high Are the graves of dreams allowed to die. -- Richard Harter -- http://mail.python.org/mailman/listinfo/python-list
Re: why import wx doesn't work?
They both work, thanks for your instruction ( : I suspect you are mixing program code for the namespace version (import wx) with the old method of importing (from wxPython.wx import *). Here are two version of a very simple app... try both and see if you get any errors. And if so, _please_ post the exact error you get. --- BEGIN The new namespace version import wx class MainFrame(wx.Frame): def __init__(self, parent, id=-1, title=Test Wx, size=(-1, -1), pos=(-1,-1), style=wx.DEFAULT_FRAME_STYLE|wx.NO_FULL_REPAINT_ON_RESIZE): wx.Frame.__init__(self, parent, id, title, size, pos, style) self.Show(True) app = wx.PySimpleApp() frame = MainFrame(None, -1, Test Wx NameSpace Style) app.MainLoop() --- END The new namespace version --- BEGIN The old style import from wxPython.wx import * class MainFrame(wxFrame): def __init__(self, parent, id=-1, title=Test Wx, size=(-1, -1), pos=(-1,-1), style=wxDEFAULT_FRAME_STYLE|wxNO_FULL_REPAINT_ON_RESIZE): wxFrame.__init__(self, parent, id, title, size, pos, style) self.Show(True) app = wxPySimpleApp() frame = MainFrame(None, -1, Test Wx Old Style) app.MainLoop() --- END The old style import Hope that helped! Thanks, -Kartic -- http://mail.python.org/mailman/listinfo/python-list
Re: why import wx doesn't work?
Bright ( ; You show me a crystal clear explaination. As a newbie in python and even oop, I find the python documentation is not easy to figure out. That's great with you guys so nice here. This is very good! wxApp is never defined if you use import wx. You must use wx.wxApp instead. If you import a module using import anything, then all the names imported from the module must begin with anything.. If you import wx using import wx, then ALL the wx commands, classes and variables (all the names) MUST begin with 'wx.. Change them, and your program will work. from wx import * is a special shortcut, allowing you to use all the names without wx.. If you change from something import * to import something, your code will always break, this is normal. regards, Filip Dreger -- http://mail.python.org/mailman/listinfo/python-list
Re: OOP
Although I am a newbie in programming, I read from a java book (in my native language) saying that the purpose of Object Oriented Programming are: 1. Use a real world concept in constructing program (here everything are objects with there properties and methods/actions); 2. Simplify coding; 3. and most important, faciliate the reuse of code (class, function, etc.) Hey yall, I'm new to Python and I love it. Now I can get most of the topics covered with the Python tutorials I've read but the one thats just stumping me is Object Orientation. I can't get the grasp of it. Does anyone know of a good resource that could possibly put things in focus for me? Thanks. -- http://mail.python.org/mailman/listinfo/python-list
Re: Can .py be complied?
Thx very much, I got the point now ( ; The latter. It's not completely self contained, there is an ..exe and some dll files that need to be distributed together. It's explained very clearly by the py2exe web site: http://starship.python.net/crew/theller/py2exe/ Never used google before? Just go to www.google.com and type in py2exe. Click search. It's the first hit. -- Grant Edwards grante Yow! Is something VIOLENT at going to happen to a visi.comGARBAGE CAN? -- http://mail.python.org/mailman/listinfo/python-list
why import wx doesn't work?
I just learn to make a blank windows frame with python and wxpython. I found the statment import wx cannot work as the original from wxPython.wx import *. I see in the readme file of wxpython that if I install it as the default one, I can use import wx instead of the long one. What is wrong? The code pasted below: import wx # the default is from wxPython.wx import *, I change it and it just can't work. class MyApp(wxApp): def OnInit(self): frame = wxFrame(NULL, -1, Hello from wxPython) frame.Show(true) self.SetTopWindow(frame) return true app = MyApp(0) app.MainLoop() -- http://mail.python.org/mailman/listinfo/python-list
Re: why import wx doesn't work?
Which version of wxPython are you running? What do you mean by does not work...does the import fail or is your code giving errors? It is the current new version 2.6. The error message said that the class wxApp is not defined... But when using the default from wxPython.wx import *, it works. -- http://mail.python.org/mailman/listinfo/python-list
Re: Can .py be complied?
python -o foo.exe foo.py Is that a real command that can be use? -- http://mail.python.org/mailman/listinfo/python-list
Re: why import wx doesn't work?
It is the current version of wxPython(2.6). But follow you instruction it still can't work... But if using the default from wxPython.wx import *, it work, don't know what is the problem. May be this is an old example that cannot work with import wx. Because I get another example and it is ok. Anyway, I hope I can catch up with you guys here in python programming soon. Thanks a lot ( : Assuming you've installed a version of wxPython that is recent enough that import wx works (it's really unclear from what you've written above), then the problem you are facing is not using the namespace that you've now imported. Do this instead: class MyApp(wx.App): def OnInit(self): frame = wx.Frame(NULL, -1, Note that wx. before everything from wxPython... -Peter -- http://mail.python.org/mailman/listinfo/python-list
Which IDE is recommended?
Read through python site for programming tool, really plenty of choices :-) (For c++, I just can't breath with very very limited choices) Tried Spe, it come with wxGlade built-in very nice(is Spe still actively develop?). But seem that Boa Constructor and PyDev(the plug-in for Eclipse) also worth looking. Actually which one are you guys using? and why? I think it is also valuable for those who are new to python as me. -- http://mail.python.org/mailman/listinfo/python-list
Re: Can .py be complied?
And then example.pyc will appear beside example.py. This new file does not require example.py (you can even delete it), and works on any computer with Python installed Filip, you can read through my mind (-: You just told me what I want to know exactly, even I can't ask the question correctly. Thx.. python24\python -OO) and then import your example.py, you will get a file example.pyo, which is also stripped of any documentation strings (a bit harder to decode). Is .pyo still not secure for serious purpose? The -OO function refer to which area of python that I can read a doc in details? The end-user needs the JRE, not Python. Kent Actually I still not dare to touch Jython, because I am still digging python now. But the JRE may not attract end-user, because it is still associate with slow and eating much system resource, although Java is sure a respectfully programming language. What do you think? -- http://mail.python.org/mailman/listinfo/python-list
Re: Can .py be complied?
But those files can be decompyled. Hi, so which way to go? -- http://mail.python.org/mailman/listinfo/python-list
Re: Which IDE is recommended?
What about eric? Good, it seem a very capable ide. But it require qt and for linux only? (can't find the system requirement) I have been using PyDev for some time, but i think it is not always very handsome (e.g. writing a 5-line script in vim needs less time than eclipse startup ;-) otoh, for 5line scripts i am using vim anyway... Yes, eclipse really eat my ram out -- http://mail.python.org/mailman/listinfo/python-list
Re: Can .py be complied?
py2exe has nothing to do with C or make files. You create a setup.py file containing a couple lines of python. You run that python program, and you end up with an .exe file and some associated .dll files. I typically use inno-setup to create an installer.exe that creates a desktop icon and start-menu entry, but that's optional. Is py2exe used to make a .exe file to install .py, or make the self-contain .exe file of the program itself? -- http://mail.python.org/mailman/listinfo/python-list
Re: Which IDE is recommended?
* Don't underestimate IDLE, it's surprisingly capable considering it's just a dinky little thing Yes, I believe IDLE is the a unbeatible last resort for python (-: * SPE has great features, but the pure-Python-ness makes it slow! Is it related to wxpython you mean? or program with GUI in tk (the default installed with python) is faster? Would you mind to tell me more... -- http://mail.python.org/mailman/listinfo/python-list
Can .py be complied?
Hi all, I am new to programming, already have a glace on introduction of c++, java and finally decided on python. But I found that the .py file is just like the source file, how can I make a program without revealing its source? (may be my question is a little bit stupid) -- http://mail.python.org/mailman/listinfo/python-list