Re: The following modules appear to be missing ['_sysconfigdata']
OK, stop the presses. Or, rather, refresh your browser, I guess. In a 'what the !@#$ am I doing'-moment (I don't get those often) I uninstalled everything and went gardening. But it was raining so I installed everything again, this time using pip for wxpython. Lo and behond, this time it did not crash the cmd-window, but in stead it successfully installed it. Woot. Then I compiled again with same command and same setup-py and - stubbornly - with py2exe, and got… different errors! That's actually I good sign. No, really. Because this time, the error was about missing Windows DLLs and for these I got plenty of help from my best friend Google (don't tell JackD he's actually second best friend). So, after x iterations I ended up with the following cute setup.py: <- from distutils.core import setup import py2exe setup(console=['AutoArchive.py'], options={ 'py2exe': { 'dll_excludes': ['api-ms-win-core-string-l1-1-0.dll', 'api-ms-win-core-psapi-l1-1-0.dll', 'api-ms-win-core-registry-l1-1-0.dll', 'api-ms-win-core-localization-l1-2-0.dll', 'api-ms-win-security-base-l1-1-0.dll', 'api-ms-win-core-string-obsolete-l1-1-0.dll', 'api-ms-win-core-delayload-l1-1-0.dll', 'api-ms-win-core-handle-l1-1-0.dll', 'api-ms-win-crt-private-l1-1-0.dll', 'api-ms-win-core-libraryloader-l1-2-1.dll', 'api-ms-win-core-memory-l1-1-0.dll', 'api-ms-win-core-heap-obsolete-l1-1-0.dll', 'api-ms-win-core-atoms-l1-1-0.dll', 'api-ms-win-core-processthreads-l1-1-1.dll', 'api-ms-win-core-heap-l2-1-0.dll', 'api-ms-win-core-delayload-l1-1-1.dll', 'api-ms-win-core-processthreads-l1-1-0.dll', 'api-ms-win-core-com-midlproxystub-l1-1-0.dll', 'api-ms-win-crt-string-l1-1-0.dll', 'api-ms-win-crt-runtime-l1-1-0.dll', 'api-ms-win-core-libraryloader-l1-2-0.dll', 'api-ms-win-core-errorhandling-l1-1-0.dll', 'api-ms-win-core-string-l2-1-0.dll', 'api-ms-win-core-synch-l1-2-0.dll', 'api-ms-win-core-profile-l1-1-0.dll', 'api-ms-win-core-synch-l1-1-0.dll', 'api-ms-win-core-threadpool-legacy-l1-1-0.dll', 'api-ms-win-core-interlocked-l1-1-0.dll', 'api-ms-win-core-debug-l1-1-0.dll', 'api-ms-win-core-sysinfo-l1-1-0.dll'] } }, ) -> After which all the missing DLL errors were finally gone (and no, I don’t wanna know why all of the above is even necessary). Success!! Or not? Because I was now right back at: <- The following modules appear to be missing ['Carbon.Appearance', '_sysconfigdata'] -> You cannot possibly be serious!? _sysconfigdata is back… with a friend! Luckily it was still raining so my plan to blow up the PC in my garden fire pit (and dancing hysterically around the glorious resulting bonfire, while in the nude) got scrapped, which allowed me to notice that an actual dist folder had in fact been created, and not just that, there was an EXE inside! So I ran it. and it worked. It worked! It did exactly what it needed to do. Just like on my old machine. I even got the fancy progress popup and the date string in my file names. (At this point I ~did~ dance in the nude, albeit in front of the PC) So what lessons did I learn: 1) compile errors apparently mean Sweet-BLEEP-All; 2) close the curtains when dancing naked around the PC; 3) the back of modern day PCs, which typically sit at groin height on your desk, get really hot at the back. Avoid contact with exposed and/or dangling body parts; 4) there's clearly a reason why I 'gave up on Python' those 10 years ago, and perhaps I'm slowly starting to remember why… :| Jimbo. -- https://mail.python.org/mailman/listinfo/python-list
Re: The following modules appear to be missing ['_sysconfigdata']
OK, stop the presses. Or, rather, refresh your browser, I guess. In a 'what the !@$$ am I doing'-moment (I don't get those often) I uninstalled everything and went gardening. But it was raining so I installed everything again, this time using pip for wxpython. Lo and behond, this time it did not crash the cmd-window, but in stead it successfully installed it. Woot. Then I compiled again with same command and same setup.py and - stubbornly - with py2exe, and got… different errors! That's actually a good sign. No, really. Because this time, the error was about missing Windows DLLs and here I got plenty of help from my best friend Google (don't tell JackD he's actually second best friend). So, after x iterations I ended up with the following cute setup.py: <- from distutils.core import setup import py2exe setup(console=['AutoArchive.py'], options={ 'py2exe': { 'dll_excludes': ['api-ms-win-core-string-l1-1-0.dll', 'api-ms-win-core-psapi-l1-1-0.dll', 'api-ms-win-core-registry-l1-1-0.dll', 'api-ms-win-core-localization-l1-2-0.dll', 'api-ms-win-security-base-l1-1-0.dll', 'api-ms-win-core-string-obsolete-l1-1-0.dll', 'api-ms-win-core-delayload-l1-1-0.dll', 'api-ms-win-core-handle-l1-1-0.dll', 'api-ms-win-crt-private-l1-1-0.dll', 'api-ms-win-core-libraryloader-l1-2-1.dll', 'api-ms-win-core-memory-l1-1-0.dll', 'api-ms-win-core-heap-obsolete-l1-1-0.dll', 'api-ms-win-core-atoms-l1-1-0.dll', 'api-ms-win-core-processthreads-l1-1-1.dll', 'api-ms-win-core-heap-l2-1-0.dll', 'api-ms-win-core-delayload-l1-1-1.dll', 'api-ms-win-core-processthreads-l1-1-0.dll', 'api-ms-win-core-com-midlproxystub-l1-1-0.dll', 'api-ms-win-crt-string-l1-1-0.dll', 'api-ms-win-crt-runtime-l1-1-0.dll', 'api-ms-win-core-libraryloader-l1-2-0.dll', 'api-ms-win-core-errorhandling-l1-1-0.dll', 'api-ms-win-core-string-l2-1-0.dll', 'api-ms-win-core-synch-l1-2-0.dll', 'api-ms-win-core-profile-l1-1-0.dll', 'api-ms-win-core-synch-l1-1-0.dll', 'api-ms-win-core-threadpool-legacy-l1-1-0.dll', 'api-ms-win-core-interlocked-l1-1-0.dll', 'api-ms-win-core-debug-l1-1-0.dll', 'api-ms-win-core-sysinfo-l1-1-0.dll'] } }, ) -> After which all the missing DLL errors were finally gone (and no, I don’t wanna know why all of the above is even necessary). Success!! Or not? Because I was now right back at: <- The following modules appear to be missing ['Carbon.Appearance', '_sysconfigdata'] -> You cannot possibly be serious!? _sysconfigdata is back… with a friend! Luckily it was still raining so my plan to blow up the PC in my garden fire pit (and dancing hysterically around the glorious resulting bonfire, while in the nude) got scrapped, which allowed me to notice that an actual dist folder had in fact been created, and not just that, there was an EXE inside! So I ran it. and it worked. It worked! It did exactly what it needed to do. Just like on my old machine. I even got the fancy progress popup and the date string in my file names. (At this point I ~did~ dance in the nude, albeit in front of the PC) So what lessons did I learn: 1) compile errors apparently mean Sweet-BLEEP-All; 2) close the curtains when dancing naked around the PC; 3) the back of modern day PCs, which typically sit at groin height on your desk, get really hot at the back. Avoid contact with exposed body parts; 4) there's clearly a reason why I 'gave up on Python' those 10 years ago, and perhaps I'm slowly starting to remember why… :| Jimbo. -- https://mail.python.org/mailman/listinfo/python-list
Re: The following modules appear to be missing ['_sysconfigdata']
Oh, another thing. I installed WX via a windows installer that I found (can't find the link again, but fairly certain it was this one: https://sourceforge.net/projects/wxpython/ (*)), without giving it much thought (yesyes bad mistake). Since I get wx runtime errors, I'm assuming I have the wrong version. So, in all my 45-yo youthful ignorance, I ran 'pip install -U wxPython' hoping it would magically erase the previously installed version - whatever that is - and get me the newest one. What actually happens is the cmd-window freezing, and nothing else… (*) The 'proper' method to install it, I obviously found on "https://wiki.wxpython.org/How%20to%20install%20wxPython#Windows;, but that led me to 'pip', which at that moment in time - 2 days ago LOL - I was not ready for yet (Hey, I'm doing this in between actual work, putting kids in bed, and passing out on the sofa) -- https://mail.python.org/mailman/listinfo/python-list
Re: The following modules appear to be missing ['_sysconfigdata']
Really, no-one? OK, more purging then. I ~think~ I need said missing component because the script gets the system date (to run once on a Friday, in automatic mode). But I've never used it in automatic mode (since I came to my senses about having an infinite looping script in my autoexec.bat, doing nothing, except executing once on a friday, and wasting resources). So, if I scrap the automatic mode, I guess I might finally have something that 'works'. Still disappointed though that I can't get it to work again with the same 'tools' as previously. Especially since I also use the date to add to the name of the backup files that the script is making. Oh, as for 'distributing' this thing. It's a private/personal script, so I'm my only customer. In this sense, I don't even need the EXE now that I've scrapped automatic mode. I can just run the *.py straight from a console. Oh well. Would anyone be interested in seeing the - now infamous - script, to have a go yourself? -- https://mail.python.org/mailman/listinfo/python-list
Re: The following modules appear to be missing ['_sysconfigdata']
Well that escalated quickly :). So, no-one can tell me which component to pip to get rid of "missing ['_sysconfigdata']" error? -- https://mail.python.org/mailman/listinfo/python-list
Re: The following modules appear to be missing ['_sysconfigdata']
On Wednesday, January 9, 2019 at 6:06:35 AM UTC+1, Matthew Lemon wrote: > Hi, > > I would start from scratch with this. > > 1. You have latest Python 2 version. > 2. Use virtualenv to create and activate a new virtual environment. > 3. pip install wxPython and other dependencies. > 4. Get your application running from the command line first and follow up any > DLL exceptions. > 5. Use pyinstaller (https://pyinstaller.readthedocs.io/en/stable/) to create > a new exe file once you know everything works. > > Matt > > On 8 January 2019 10:38:16 GMT, I wrote: > >Hello, > > > >first time using python groups (and long time since using any other > >group for that matter). This might not be the right group due to wx > >being involved. > > > >Long story as short as possible. I have an old python script that I did > >~10 years ago, and have forgotten basically everything about Python > >since then (sorry!). Converted it to EXE way back when, and have kept > >using the EXE ever since then (on XP, and on Win7). > > > >I've just gotten a new PC, Windows10 (!), needed to update the script, > >so needed to recompile the EXE, and now it no longer compiles/works. It > >was fine on Windows7 (I'm not specifically stating that the problem is > >with windows10 - I simply don't remember all the hoops I jumped through > >on my previous machine). > > > >Here is the compile error: > >The following modules appear to be missing > >['_sysconfigdata'] > > > >And here is the runtime error: > >Traceback (most recent call last): > > File "AutoArchive.py", line 3, in > > File "wx\__init__.pyc", line 45, in > > File "wx\_core.pyc", line 4, in > > File "wx\_core_.pyc", line 12, in > > File "wx\_core_.pyc", line 10, in __load > >ImportError: DLL load failed: %1 is not a valid Win32 application. > > > >Here is how I compile: python setup.py py2exe > > > >And this is my setup.py: > >from distutils.core import setup > >import py2exe > > > >setup(console=['AutoArchive.py']) > > > >Yes, that says 'console' for a Windows EXE, but swapping it to 'window' > >didn't help. Besides which, the setup.py file is straight from the old > >computer, so 'it used to work'. > > > >What I have installed: > >. python 2.7.13 (this in itself may be a problem - I don't even > >remember which version I was using earlier, other than knowing for sure > >it wasn't a 3.x release) > >. wxpython (since I also got an error that wx module was missing - > >that rang some bells, since the script uses a Windows pop-up window to > >inform me about its progress, and I remember using wx for that, so I > >installed it, but don't know how to get its' version. using "python -c > >"import wx;print wx.__version__" just gives runtime errors). > > > >Any help would be appreciated. > > > >And yes, I googled, but can't really find anything (well, d'Uh!, I > >wouldn’t be here then would I?) - there's ~some~ references, but > >usually it's about similar issues on Linux, with solutions that are not > >applicable at all. Except one I thought: I found some link stating that > >_sysconfigdata is part of sysconfig, and that this needed to be > >installed with pip, so I used the pip that came with my python distro > >and did 'pip install [[_]sys]config[data]' (all possible combo's) but > >pip claims it can't find said module, and TBH, I can't seem to find > >anything myself about said module. > > > >Thx, > >Jimbo > >-- > >https://mail.python.org/mailman/listinfo/python-list > > -- > Sent from my Android device Thx for your feedback. I am a tad afraid you're giving me a bit too much credit though; it's all a bit Chinese to me. (I'm not Chinese, BTW, but I'm not making up these expressions myself so there's that). Step 2 you've lost me already. What is virtualenv, and why do I need it (this time round, not last time when I got it to work)? You don’t really need to respond, this is more of a rethorical question :). Step 3 is I think the real issue. At first I was missing 'wx' and '_sysconfigdata', so I installed wxPhyton (via a windows installer that I found, not with pip), and that made the compile error go away (though it still throws runtime errors, of course). But what is '_sysconfigdata', and how do I install it? I - and pip :) - can't find a repo with that name!? step 5, pyinstaller, is yet another hurdle I hope to avoid. It worked with py2exe, and it should still work with py2exe (within the efforts I'm prepared to put into this). Of
The following modules appear to be missing ['_sysconfigdata']
Hello, first time using python groups (and long time since using any other group for that matter). This might not be the right group due to wx being involved. Long story as short as possible. I have an old python script that I did ~10 years ago, and have forgotten basically everything about Python since then (sorry!). Converted it to EXE way back when, and have kept using the EXE ever since then (on XP, and on Win7). I've just gotten a new PC, Windows10 (!), needed to update the script, so needed to recompile the EXE, and now it no longer compiles/works. It was fine on Windows7 (I'm not specifically stating that the problem is with windows10 - I simply don't remember all the hoops I jumped through on my previous machine). Here is the compile error: The following modules appear to be missing ['_sysconfigdata'] And here is the runtime error: Traceback (most recent call last): File "AutoArchive.py", line 3, in File "wx\__init__.pyc", line 45, in File "wx\_core.pyc", line 4, in File "wx\_core_.pyc", line 12, in File "wx\_core_.pyc", line 10, in __load ImportError: DLL load failed: %1 is not a valid Win32 application. Here is how I compile: python setup.py py2exe And this is my setup.py: from distutils.core import setup import py2exe setup(console=['AutoArchive.py']) Yes, that says 'console' for a Windows EXE, but swapping it to 'window' didn't help. Besides which, the setup.py file is straight from the old computer, so 'it used to work'. What I have installed: . python 2.7.13 (this in itself may be a problem - I don't even remember which version I was using earlier, other than knowing for sure it wasn't a 3.x release) . wxpython (since I also got an error that wx module was missing - that rang some bells, since the script uses a Windows pop-up window to inform me about its progress, and I remember using wx for that, so I installed it, but don't know how to get its' version. using "python -c "import wx;print wx.__version__" just gives runtime errors). Any help would be appreciated. And yes, I googled, but can't really find anything (well, d'Uh!, I wouldn’t be here then would I?) - there's ~some~ references, but usually it's about similar issues on Linux, with solutions that are not applicable at all. Except one I thought: I found some link stating that _sysconfigdata is part of sysconfig, and that this needed to be installed with pip, so I used the pip that came with my python distro and did 'pip install [[_]sys]config[data]' (all possible combo's) but pip claims it can't find said module, and TBH, I can't seem to find anything myself about said module. Thx, Jimbo -- https://mail.python.org/mailman/listinfo/python-list
[issue33129] Add kwarg-only option to dataclass
Jimbo Jim added the comment: first post in bugs.python.org... are people normally scary around here? Another usecase of keyword-only arguments is that I can mix default and non-default fields in any order. This could be achieved by either marking all fields as read-only, or by implicitly adding an asterisk before the first "conflicting" non-default argument (or by translating .../etc into an asterisk). (Is it a bad idea to create a private fork of `pip install dataclasses` with implicit asterisk, purely for my own project?) -- nosy: +Jimbo Jim ___ Python tracker <https://bugs.python.org/issue33129> ___ ___ Python-bugs-list mailing list Unsubscribe: https://mail.python.org/mailman/options/python-bugs-list/archive%40mail-archive.com
Re: Import Problem on WIndows py3
On Tuesday, September 4, 2012 1:45:55 PM UTC-7, Werner Thie wrote: On 9/4/12 9:49 AM, jimmyli1528 wrote: I have a main program and a 3rd party module. Trying to import colorama, where colorama is a folder with files in it, returns an ImportError: No module named colorama. How should I import folders? Do you have a (empty) __init__.py file present in this particular directory? Werner OK works perfectly! -- http://mail.python.org/mailman/listinfo/python-list
[WxPython] Advice on Temperature Application Method Structure
Hello I have made a simple application using WxPython that is a temperature converter. This is my first application made in WxPython, the only other apps I have made were in Win32 c++ so I am new to widgets in general. I am looking for advice criticism on when you should use classes in GUI widget apps ( where) other general advice: - Structure of a wxPython script/code - Should every window be in its own class? - whats the best way to refer to a control (by window name or ID) - Should a group of controls that are related be in a class For example should I make a Celsius class that handles the celsius editbox, static button the button action function(convert_to_fahrenheit())? - Errors, bad things I have done in my code - When why use a Validator?? Temperature Converter Application: Temperature Application Description: This application uses WxPython to create a simple windows app to convert temperature from celsius to fahrenheit visa versa. Looking for advice on everything to do with wxPython: For example: - Structure of a wxPython script/code - Should every window be in its own class? - whats the best way to refer to a control (by window name or ID) - Should a ground of controls that are related be in a class For example should I make a Celsius class that handles the celsius editbox, static button? - Errors, bad things I have done in my code - When why use a Validator?? import wx ## Constants ## ID_FAHREN = 1 ID_CELSIUS = 2 class Controller(wx.Frame): def __init__(self, parent, id): wx.Frame.__init__(self,parent,id,Temperature Converter, size=(247,186)) # Create Controls panel = wx.Panel(self) self.create_controls( panel, wx.Validator() ) self.fah_edit.SetValue(str(32)) self.cel_edit.SetValue(str(0)) # Define actions self.Bind_Events() def create_controls(self, panel, val): Create all the controls we will need for the temperature conversion self.bmp_static = wx.StaticText(panel, -1, Bitmap pic will be here, (10,5), (150,40)) self.fah_static = wx.StaticText(panel, -1, Fahrenheit: , (10,70), (-1,-1)) self.cel_static = wx.StaticText(panel, -1,Celsius: , (140,70), (-1,-1)) self.fah_edit = wx.TextCtrl(panel,ID_FAHREN, pos=(70,65), size=(40,25), style=0, validator=val, name='a') self.cel_edit = wx.TextCtrl(panel,ID_CELSIUS, pos=(180,65), size=(40,25), style=0, validator=val, name='b') self.to_fah_button = wx.Button(panel,label=To Fahrenheit, pos=(145,95),size=(80,25)) self.to_cel_button = wx.Button(panel,label=To Celsius, pos=(35,95),size=(80,25)) self.exit_button = wx.Button(panel,label=Exit,pos=(157,123), size=(70,25)) def Bind_Events(self): Bind application events to class functions self.Bind(wx.EVT_BUTTON,self.close_button, self.exit_button) self.Bind(wx.EVT_CLOSE,self.close_window) self.Bind(wx.EVT_BUTTON,self.convert_to_celsius, self.to_fah_button) self.Bind(wx.EVT_BUTTON,self.convert_to_fahrenheit, self.to_cel_button) def close_button(self, event): self.Close(True) def close_window(self, event): self.Destroy() def error_check(self, string): Check for valid input in editboxes. Valid input includes float integer values only if string.isalpha() or len(string) = 0: return False return True def convert_to_fahrenheit(self, event): Convert the value in fahrenheit window to celsius display in our window/edit box # Algorithm # - Get number from fahrenheit editbox # - convert fahrenheit value to celsius # - change value in Celsius Window to # Step 1: fahren_value = self.fah_edit.GetValue() if not self.error_check( fahren_value ): self.fah_edit.SetValue( NA ) return # Step 2: value = (float(fahren_value) - 32) * 5/9 # Step 3: self.cel_edit.SetValue( str(value) ) def convert_to_celsius(self, event): Convert the value in celcius window/editbox to fahrenheit display in our window/editbox # Algorithm # - Get number from celsius editbox # - convert celsius value to fahrenheit # - change value in fahrenheit Window # Step 1: celsius_value = self.cel_edit.GetValue() if not self.error_check( celsius_value ): self.cel_edit.SetValue( NA ) return # Step 2: value = (float( celsius_value ) * 9/5) + 32 # Step 3: self.fah_edit.SetValue( str(value) ) if __name__ == __main__: app = wx.PySimpleApp() frame = Controller(parent=None,id=-1) frame.Show() app.MainLoop() -- http://mail.python.org/mailman/listinfo/python-list
Extract all words that begin with x
Hello I am trying to find if there is a string OR list function that will search a list of strings for all the strings that start with 'a' return a new list containing all the strings that started with 'a'. I have had a search of Python site I could not find what I am looking for, does a function like this exist? The only one that I think could work is, use the string function .count() algorithm: to exract all the words inside a list that start with 'a' - make sure the list is arranged in alphabetical order - convert the list to a big string - use list_string.count(',a') to obtain the index where the last 'a' word occurs - convert back into string (yes this is a REAL hack :P) - and then create a new list, ie, new_list = list[0:32] - return new_list Ok that algorithm is terrible, I know, I just realise that it wont work for letters after 'a'. So if anyone could suggest a function or algorithm it would be extremely helpful -- http://mail.python.org/mailman/listinfo/python-list
Use Regular Expressions to extract URL's
Hello I am using regular expressions to grab URL's from a string(of HTML code). I am getting on very well I seem to be grabbing the full URL [b]but[/b] I also get a '' character at the end of it. Do you know how I can get rid of the '' char at the end of my URL [b]Example of problem:[/b] [quote] I get this when I extract a url from a string http://google.com; I want to get this http://google.com [/quote] My regular expression: [code] def find_urls(string): Extract all URL's from a string return as a list url_list = re.findall(r'(?:http://|www.).*?[]',string) return url_list [/code] -- http://mail.python.org/mailman/listinfo/python-list
Fast Efficient way to transfer an object to another list
Hello I have a relatively simple thing to do; move an object from one to list into another. But I think my solution maybe inefficient slow. Is there a faster better way to move my stock object from one list to another? (IE, without having to use a dictionary instead of a list or is that my only solution?) [code] class stock: code = NULL price = 0 stock_list1 = [] stock_list2 = [] def transfer_stock(stock_code, old_list, new_list): Transfer a stock from one list to another # is there a more efficient faster way to index = 0 for stock in old_list: temp_stock = stock if temp_stock.code == stock_code: new_list.append(temp_stock) del old_list[index] index += 1 return new_list[/code] -- http://mail.python.org/mailman/listinfo/python-list
Print Error Type when I catch it
Hello I have a relatively simple question. I want to use a try except in a function when an error occurs I want to print the error type name(eg IOError, OSError etc) do you know how I can do this without specifying all possible errors, eg having to do this except (IOError, OSError, IndexError, ): try: ... some code except: # Here I want to print type of error that occured print errorType The reason I want to do this is because one of my complex programs is crashing BUT no python error message is comming up in red when I run it, so I cant figure out what error occured? So I think its time I learnt to print out my own errors their types -- http://mail.python.org/mailman/listinfo/python-list
Error Occurs: Replace a character in a String
Hello, I am getting an error in my python script when I try to change a character in a string. [b]But I dont know why or what to do to fix it?[/b] I have commented in my code where the error occurs [code] def format_file(filename): HTML_file = open(filename,'r') HTML_source = HTML_file.read() HTML_file.close() x = 0 # Format all ID's classes correctly temp_buf= HTML_source.lower() class_occurence = temp_buf.count('class') ID_occurence= temp_buf.count('id') for n in range(class_occurence): hit = temp_buf.find('class') if not hit==-1: temp_buf[hit] = '~' # Error: 'str' object does not support item assignment x = hit+5 # delete any spaces until we reach a letter or number while xtemp_buf[x]: if temp_buf[x] == ' ': tempbuf[x] = '' HTML_source[x] = '' elif temp_buf[x] == '=': pass #elif temp_buf[x] == ' or temp_buf[x] == '' isalpha(temp_buf[x]) else: break x += 1 [/code] -- http://mail.python.org/mailman/listinfo/python-list
Simple Cookie Script: Not recognising Cookie
Hi I have a simple Python program that assigns a cookie to a web user when they open the script the 1st time(in an internet browser). If they open the script a second time the script should display the line You have been here 2 times. , if they open the script agai it should show on the webpage You have been here 3 times and so on. But for some reason, my program is not assigning or recognising an assigned cookie outputing the line You have been here x times. I have gone over my code for like 2 hours now I cant figure out what is going wrong?? Can you help me figure out whats wrong? I have my own cgi server that just runs on my machine so its not that its the code to recognise/ assign a cookie [code]#!/usr/bin/env python import Cookie import cgi import os HTML_template = html head /head body p %s /p /body /html def main(): # Web Client is new to the site so we need to assign a cookie to them cookie = Cookie.SimpleCookie() cookie['SESSIONID'] = '1' code = No cookie exists. Welcome, this is your first visit. if 'HTTP_COOKIE' in os.environ: cookie = Cookie.SimpleCookie(os.environ['HTTP_COOKIE']) # If Web client has been here before if cookie.has_key('SESSIONID'): cookie['SESSIONID'].value = int(cookie['SESSIONID'].value) +1 code = You have been here %s times. % cookie['SESSIONID'].value else: cookie = Cookie.SimpleCookie() cookie['SESSIONID'] = '1' code = I Have a cookie, but SESSIONID does not exist print Content-Type: text/html\n print HTML_template % code if __name__ == __main__: main() [/code] -- http://mail.python.org/mailman/listinfo/python-list
Advice Criticism on Python App
I have made a Python App(really script) that will check a stocks current values from a website save that data to a SQLite 3 database. I am looking for any suggestions criticisms on what I should do better or anything at all but mainly in these areas: [QUOTE] - Correct Python Layout of code - Correct error checking: Am I catching all my errors or are my exceptions not specific enough? Should I be using more try excepts inside my functions? - Are there any areas where huge errors, bugs etc could occur that I have not compensated for? - I am also looking for suggestions on how to write a function better, so if you think that function is really bad should be rewritten completely or something I would really like to hear it. - Anything else that you see - Is python meant to be used in the way I have used it? To make a 'semi detailed' app?[/QUOTE] Any advice criticism would be really helpful. App: [CODE] *Stock Data Builder* Algorithm: - Search website for stock - Get website HTML source code - Search code for target stock data(price,dividends,etc..) - Add data to text file import sys import os import sqlite3 import datetime import time import urllib2 ### Global Variables ### menu = ***Stock Program*** \n\n1. Add a Stock to track \n2. Get Todays Tracking Data \n3. Exit \nEnter decision: target = 'th scope=row class=rowa href=/asx/research/ companyInfo.do?by=asxCodeasxCode=%s%s/a' ASXurl = 'http://www.asx.com.au/asx/markets/priceLookup.do? by=asxCodesasxCodes=' class stock: code = purchasePrice= 0 purchaseQuantity = 0 price= [] # list of recent prices recentBid= [] # list of recent bids for stock recentOffer = [] # list of recent offers for stock stockVol = [] # list of stock quantity available on market def __init__(self): Default Constructor self.code = self.purchasePrice= 0 self.purchaseQuantity = 0 def constructor(self, stockCode, purPrice, purQuant): Constructor self.code = stockCode self.purchasePrice= purPrice self.purchaseQuantity = purQuant def setData(self, stockCode, purPrice, purQuant, priceList, reBidList, reOffList, popList): Defines implements the objects' public variables self.code = stockCode self.purchasePrice= purPrice self.purchaseQuantity = purQuant self.price= priceList self.recentBid= reBidList self.recentOffer = reOffList self.stockVol = popList self.printStats() def updateData(self, priceEle, bidEle, offerEle, populEle): Adds data to stock object's lists self.price.append(priceEle) self.recentBid.append(bidEle) self.recentOffer.append(offerEle) self.stockVol.append(populEle) def printStats(self): Output Stock attributes print(Stock Code: +self.code) print(Stock Purchase Price: +str(self.purchasePrice)) print(Stock Quantity Owned: +str(self.purchaseQuantity)) print(***Initial Investment Value: +str(self.purchasePrice*self.purchaseQuantity)) if not(len(self.price) = 0): print(Stock Current Price: +str(self.price[-1])) print(Recent Bid: +str(self.recentBid[-1])) print(Recent Offer: +str(self.recentOffer[-1])) print(Total Stock Volume in market: +str(self.stockVol[-1])) print(***Present Investment Value: +str(self.price[-1]*self.purchaseQuantity)) print(\n) ### Functions ### def connectDatabase(dbLocation, dbName, tableName): Establish Return connection to SQLite Database try: if not (os.path.exists(dbLocation)): os.mkdir(dbLocation) # create folder/dir os.chdir(dbLocation)# change directory focus to dbLocation conn = sqlite3.connect(dbLocation+dbName) cur = conn.cursor() try: createTableQ = CREATE TABLE IF NOT EXISTS +tableName + (code varchar PRIMARY KEY, purchase_price float, purchase_quantity float, purchase_date varchar); cur.execute(createTableQ) conn.commit() except: pass return conn except IOError or OSError: print Connection to database failed return False def retrieveStockDatabase(conn, tableName): Read SQLite3 database extract stock data into StockList stockList = [] stockQuery = select recent_price, recent_offer, recent_bid, stock_volume from ? ; cur = conn.cursor() cur.execute(select code, purchase_price, purchase_quantity from +tableName+;) for row in cur.fetchall(): newStock = stock() newStock.code = row[0] newStock.purchasePrice= row[1] newStock.purchaseQuantity = row[2] cur.execute(stockQuery,[newStock.code])
Re: Best Way to extract Numbers from String
On Mar 20, 11:51 pm, Luis M. González luis...@gmail.com wrote: On Mar 20, 12:04 am, Jimbo nill...@yahoo.com wrote: Hello I am trying to grab some numbers from a string containing HTML text. Can you suggest any good functions that I could use to do this? What would be the easiest way to extract the following numbers from this string... My String has this layout I have commented what I want to grab: [CODE] /th td class=last43.200 /td td class=change indicator nowrap0.040 /td td43.150 /td # I need to grab this number only td43.200 /td td43.130 /td # I need to grab this number only td43.290 /td td43.100 /td # I need to grab this number only td7,450,447 /td td class=middlea href=/asx/markets/optionPrices.do? by=underlyingCodeunderlyingCode=BHPexpiryDate=optionType=Options/ a/td td class=middlea href=/asx/markets/warrantPrices.do? by=underlyingAsxCodeunderlyingCode=BHPWarrants Structured Products/a/td td class=middlea href=/asx/markets/cfdPrices.do? by=underlyingAsxCodeunderlyingCode=BHPCFDs/a/td td class=middlea href=http://hfgapps.hubb.com/asxtools/ Charts.aspx? TimeFrame=D6compare=comp_indexindicies=XJOpma1=20pma2=20asxCode=BHP img src=/images/chart.gif border=0 height=15 width=15/a /td tda href=/research/announcements/status_notes.htm#XDXD/a /td tda href=/asx/statistics/announcements.do? by=asxCodeasxCode=BHPtimeframe=Dperiod=WRecent/a /td /tr[/CODE] You should use BeautifulSoup or perhaps regular expressions. Or if you are not very smart, lik me, just try a brute force approach: for i in s.split(''): for e in i.split(): if '.' in e and e[0].isdigit(): print (e) 43.200 0.040 43.150 43.200 43.130 43.290 43.100 - Hide quoted text - - Show quoted text -- Hide quoted text - - Show quoted text - Thanks very much, I'm going to look at regular expressions but that for your code, it shows me how I can do it iwth standard python :) -- http://mail.python.org/mailman/listinfo/python-list
Why this compile error?
Hello Can you help me figure out why I am getting this compile error with my program. The error occurs right at the bottom of my code I have commented where it occurs. The error is: [QUOTE]Expected an indented block[/QUOTE] [CODE] *Stock Data Builder* Algorithm: - Search website for stock - Get website HTML source code - Search code for target stock data(price,dividends) - Add data to text file import sys # Functions def getSource(URL, sourceBuffer): Retrieve HTML source code from websitr URL save in sourceBuffer return sourceBuffer def getData(targetData, dataBuffer): Searches the string dataBuffer for the occurence of target data returns that whole line def writeToFile(textFile, dataBuffer): Writes data in string dataBuffer to text file # CHANGE this to try except to catch errors fileT = open(textFile,'a') fileT.write(dataBuffer) return True; # function succeeded def writeToFile(textFile, dataList): Writes data in List dataList to text file # CHANGE this to try except to catch errors fileT = open(textFile,'a') for element in dataList: fileT.write(element) return True; # function succeeded # Main program loop def main(): programEnd = False; while (programEnd == False): #ERROR HERE?? - Error=Expected an indented block main()[/CODE] -- http://mail.python.org/mailman/listinfo/python-list
Best Way to extract Numbers from String
Hello I am trying to grab some numbers from a string containing HTML text. Can you suggest any good functions that I could use to do this? What would be the easiest way to extract the following numbers from this string... My String has this layout I have commented what I want to grab: [CODE] /th td class=last43.200 /td td class=change indicator nowrap0.040 /td td43.150 /td # I need to grab this number only td43.200 /td td43.130 /td # I need to grab this number only td43.290 /td td43.100 /td # I need to grab this number only td7,450,447 /td td class=middlea href=/asx/markets/optionPrices.do? by=underlyingCodeunderlyingCode=BHPexpiryDate=optionType=Options/ a/td td class=middlea href=/asx/markets/warrantPrices.do? by=underlyingAsxCodeunderlyingCode=BHPWarrants amp; Structured Products/a/td td class=middlea href=/asx/markets/cfdPrices.do? by=underlyingAsxCodeunderlyingCode=BHPCFDs/a/td td class=middlea href=http://hfgapps.hubb.com/asxtools/ Charts.aspx? TimeFrame=D6amp;compare=comp_indexamp;indicies=XJOamp;pma1=20amp;pma2=20amp;asxCode=BHPimg src=/images/chart.gif border=0 height=15 width=15/a /td tda href=/research/announcements/status_notes.htm#XDXD/a /td tda href=/asx/statistics/announcements.do? by=asxCodeasxCode=BHPtimeframe=Dperiod=WRecent/a /td /tr[/CODE] -- http://mail.python.org/mailman/listinfo/python-list
Python Script to get Info from Site not working
Hello I am asking what is probably a very easy thing to do but I cannot find a tutorial on how to do it anywhere. [b]I want to use a Python script to get information from a webpage. [/b] I found a semi Python internet tutorial here if anyone else would like it http://www.upriss.org.uk/python/session6.html I would like to create a python script that gets a value from a set of radio buttons on a HTML page tell me which one is selected. I have 3 radio buttons: Tea, Coffee, Hot Chocolate a Submit button My script is meant to find which radio button is selected tell me that. But it just keeps saying No Drink Selected! Can you help me figure out how to fix this. FYI: My Python script my HTML page are both saved in the same directory. And I made the webpage using Notepad++, I open the webpage in Interent Explorer I made the Python Script in Idle. Python Script: [code]# Practice 9 CGI # don't change the following three lines: ### import cgi print(Content-Type: text/html\n) form = cgi.FieldStorage() ## add a form.getvalue for each of the names in your form: ## drink = form.getvalue(drink) ## start of HTML code ### print( html head titleWhat would you like to drink/title /head body h4Your drink: /h4p ) end of HTML code # if drink == tea: print(You requested tea.) elif drink == coffee: print(You requested coffee.) elif drink == hot chocolate: print (You requested hot chocolate.) else: print (You need to select a drink!) ### start of HTML code ### print ( pThank you for your visit. Please come again. p /body/html ) # end of HTML code ## [/code] HTML Code: [code]html head /head body form action=practice9.py method=post input type=radio name=drink value=tea checked Tea br input type=radio name=drink value=coffee Coffee br input type=radio name=drink value=hot chocolate Hot Chocolate p input type=submit value=Place order /form /body /html[/code] -- http://mail.python.org/mailman/listinfo/python-list
Re: Python Script to get Info from Site not working
On Mar 11, 12:38 pm, Gabriel Genellina gagsl-...@yahoo.com.ar wrote: En Wed, 10 Mar 2010 20:06:41 -0300, Jimbo nill...@yahoo.com escribió: I found a semi Python internet tutorial here if anyone else would like ithttp://www.upriss.org.uk/python/session6.html My script is meant to find which radio button is selected tell me that. But it just keeps saying No Drink Selected! Are you sure? From the code you posted, the message should read You need to select a drink!, not that one. Replace the last line with something like this, to see what you are getting exactly: print(Sorry, no %r (%r) available. % ( drink, cgi.escape(repr(type(drink) BTW, which Python version are you using? The tutorial you linked to is aimed at Python 2.x, but your print syntax suggests you're using Python 3.x -- Gabriel Genellina Yeah that(You need to select a drink!) was the string I was getting but I should be getting hot chocolate or something else(which ever one I have selected) I am using 3.x, do you think I should be using something else? Also the your code I put in does the some thing, just now it says Sorry no none drink available all the time. -- http://mail.python.org/mailman/listinfo/python-list
bdb
Hi, I am trying to sort how to best programmatically run the debugger on a program, and another way that I am trying to explore is by using the bdb module. There isn't any documentation for this and I have tried reading through the source, which includes an example/test at the end of bdb.py on Python 2.3/OS X. What I can't figure out is how this might work if you wanted to have the function 'step' through each line. I see various functions that suggest that they might be for this but I can not get anything to work. Has anyone any suggestions or point me in the direction of any other docs? Thank you! jms. From the bdb.py: def test(): t = Tdb() t.run('import bdb; bdb.foo(10)') where Tbd subclasses Bdp and overrides the user_ methods (see around line 533 of bdb.py. But what about set_step()? Or am I way off here? -- http://mail.python.org/mailman/listinfo/python-list
debugging process
Hi, I am trying to create a separate process that will launch python and then can be used to step through a script programmatically. I have tried something like: (input, output) = os.popen2(cmd=python) Then I expected I could select over the two handles input and output, make sure they aren't going to block, and then be able to write python code to the interpreter and read it back. I intend to import a module, run it in the debugger with pdb.run() and the start passing debug commands in and read the output. I hope that makes sense, what I am finding is that whenever I try to read from the output handle it blocks. My understanding was that if it is returned by select that it is ready for reading and won't block. I think that this must have something to do with python expecting itself to by in a TTY? Can anyone give any idea of where I should be going with this? Thanks, jms. [EMAIL PROTECTED] http://www.cordiner.com -- http://mail.python.org/mailman/listinfo/python-list