Re: create new python file
So, can i program within just by the print statement? Or do i have to do something else. it is completely indecipherable (to me at least) what you are saying, leave aside any issues with python. He said, "Oh, so writing python statements into a text file is as simple as printing them, referencing a handle to the file? That seems simpler than I had imagined. Is there nothing else that I must do in order to achieve my goal?". -- http://mail.python.org/mailman/listinfo/python-list
PYTHONPATH and module names
So today, I created a file called 'formatter.py', and my program broke. It turned out that I was also import 'gluon' from web2py, which in turn, somewhere, imported the regular python formatter.py with which I was not familiar. So the question is: Does one simply always have to be knowledgeable about existing python library names, or is having '.' in the python path just a bad idea? Is there a way, not having '.' in the path to explicitly specify the current directory? Something analogous to import ./foo ? Thanks, Tobiah -- http://mail.python.org/mailman/listinfo/python-list
Re: PYTHONPATH and module names
Are you familiar with absolute and relative imports: http://docs.python.org/release/2.5/whatsnew/pep-328.html Doesn't seem to work: Python 2.7.3 (default, May 10 2012, 13:31:18) [GCC 4.2.4 (Ubuntu 4.2.4-1ubuntu4)] on linux2 Type "help", "copyright", "credits" or "license" for more information. >>> from __future__ import absolute_import >>> import .format File "", line 1 import .format ^ SyntaxError: invalid syntax >>> -- http://mail.python.org/mailman/listinfo/python-list
Re: Parsing Text file
On 07/02/2013 12:30 PM, sas4...@gmail.com wrote: Somemore can be anything for instance: Sometext mail maskit Sometext rupee dollar maskit and so on.. Is there a way I can achieve this? How do we know whether we have Sometext? If it's really just a literal 'Sometext', then just print that when you hit maskit. Otherwise: for line in open('file.txt').readlines(): if is_sometext(line): memory = line if line == 'maskit': print memory -- http://mail.python.org/mailman/listinfo/python-list
Re: how to calculate reputation
On 07/02/2013 02:43 PM, Surya Kasturi wrote: Hi all, this seems to be quite stupid question but I am "confused".. We set the initial value to 0, +1 for up-vote and -1 for down-vote! nice. I have a list of bool values True, False (True for up vote, False for down-vote).. submitted by users. [True, False, False, True] Now to calculate the total reputation should I take True = +1, False=0 [or] True = +1, False=-1 ?? for adding all. I am missing something here.. and that's clear.. anyone please help me on it? Thanks for vote in bool_votes: reputation += 2 * vote - 1 Tobiah -- http://mail.python.org/mailman/listinfo/python-list
Deciding inheritance at instantiation?
I have a bunch of classes from another library (the html helpers from web2py). There are certain methods that I'd like to add to every one of them. So I'd like to put those methods in a class, and pass the parent at the time of instantiation. Web2py has a FORM class for instance. I'd like to go: my_element = html_factory(FORM) Then my_element would be an instance of my class, and also a child of FORM. I started messing with decorators, but it became difficult for me to visualise how to do this. Thanks! Toby -- http://mail.python.org/mailman/listinfo/python-list
Re: Deciding inheritance at instantiation?
On 08/03/2012 02:55 PM, Terry Reedy wrote: On 8/3/2012 4:48 PM, Tobiah wrote: I have a bunch of classes from another library (the html helpers from web2py). There are certain methods that I'd like to add to every one of them. So I'd like to put those methods in a class, and pass the parent at the time of instantiation. Web2py has a FORM class for instance. I'd like to go: my_element = html_factory(FORM) Then my_element would be an instance of my class, and also a child of FORM. I started messing with decorators, but it became difficult for me to visualise how to do this. Use type(name, bases, content) for dynamic class creation. Very cool. Just what I was after. Thanks. Tobiah -- http://mail.python.org/mailman/listinfo/python-list
Re: [newbie] String to binary conversion
The binascii module looks like it might have something for you. I've never used it. Tobiah http://docs.python.org/library/binascii.html On 08/06/2012 01:46 PM, Mok-Kong Shen wrote: If I have a string "abcd" then, with 8-bit encoding of each character, there is a corresponding 32-bit binary integer. How could I best obtain that integer and from that integer backwards again obtain the original string? Thanks in advance. M. K. Shen -- http://mail.python.org/mailman/listinfo/python-list
Re: [newbie] String to binary conversion
On 08/06/2012 01:59 PM, Tobiah wrote: The binascii module looks like it might have something for you. I've never used it. Having actually read some of that doc, I see it's not what you want at all. Sorry. -- http://mail.python.org/mailman/listinfo/python-list
Re: Deciding inheritance at instantiation?
Interesting stuff. Thanks. On 08/06/2012 07:53 PM, alex23 wrote: On Aug 4, 6:48 am, Tobiah wrote: I have a bunch of classes from another library (the html helpers from web2py). There are certain methods that I'd like to add to every one of them. So I'd like to put those methods in a class, and pass the parent at the time of instantiation. Web2py has a FORM class for instance. I'd like to go: my_element = html_factory(FORM) Then my_element would be an instance of my class, and also a child of FORM. I've lately begun to prefer composition over inheritance for situations like this: class MyElementFormAdapter(object): def __init__(self, form): self.form = form def render_form(self): self.form.render() my_element = MyElementFormAdapter(FORM) my_element.render_form() my_element.form.method_on_form() Advantages include being more simple and obvious than multiple inheritance, and avoiding namespace clashes: class A(object): def foo(self): print 'a' class B(object): def foo(self): print 'b' class InheritFromAB(A, B): pass class AdaptAB(object): def __init__(self, a, b): self.a = a self.b = b >>> inherit = InheritFromAB() >>> inherit.foo() a >>> adapt = AdaptAB(A(), B()) >>> adapt.a.foo() a >>> adapt.b.foo() b -- http://mail.python.org/mailman/listinfo/python-list
Re: A little morning puzzle
Here is my solution: ** Incredibly convoluted and maximally less concise solution than other offerings. ** Might be better ones though. Unlikely. Zing! -- http://mail.python.org/mailman/listinfo/python-list
Re: Getting "empty" attachment with smtplib
I just found out that the attachment works fine when I read the mail from the gmail website. Thunderbird complains that the attachment is empty. Thanks, Toby On 11/14/2012 09:51 AM, Tobiah wrote: I've been sending an email blast out with smtplib and it's been working fine. I'm attaching an html doc with msg.attach(MIMEText(email, 'html')) and it displays fine. Now I need to attach a .pdf doc, but Thunderbird complains that the attachment is empty. When I view the source of the email, the headers look ok to me, and a large base64 looking mess follows: --===0152408622== Content-Type: application/pdf MIME-Version: 1.0 Content-Transfer-Encoding: base64 Content-Disposition: attachment; filename="tics.pdf" JVBERi0xLjYNJeLjz9MNCjE0IDAgb2JqDTw8L0xpbmVhcml6ZWQgMS9MIDExNzk1My9PIDE2L0Ug MTEyNjE3L04gMS9UIDExNzY0My9IIFsgNjA2IDI1M10+Pg1lbmRvYmoNICAgICAgICAgICAgICAg DQo2MSAwIG9iag08PC9EZWNvZGVQYXJtczw8L0NvbHVtbnMgNS9QcmVkaWN0b3IgMTI+Pi9GaWx0 ZXIvRmxhdGVEZWNvZGUvSURbPDg4RkMxMTM2QjQ3RDhEQzRFMjkxQkEzRDJGNEIyODBBPjxGRTNC RkM3MjNFMDg3QzRCQUEyNTUzMkM5NEI5QjNCOT5dL0luZGV4WzE0IDc4XS9JbmZvIDEzIDAgUi9M and so on. I've tried a few recipes, and this is the one I'm trying now: pdf = MIMEApplication(pdf_data, 'pdf') pdf.add_header('Content-Disposition','attachment', filename = 'tics.pdf') msg.attach(pdf) Any help is appreciated. Also, if anyone has a working recipe, I'd like to see it. Thanks! Tobiah -- http://mail.python.org/mailman/listinfo/python-list
Re: Getting "empty" attachment with smtplib
I can already say that "smtplib" is not to blame. It is (mostly) unconcerned with the internal structure of the message -- and by itself will not empty attachments. On the advice of a co-worker, I tried using web2py's gluon.tools.Mail. It was easier to accomplish the attachment, and Thunderbird opened the .pdf just fine. Thanks for the suggestions. Tobiah -- http://mail.python.org/mailman/listinfo/python-list
Re: Python math is off by .000000000000045
> For every floating point > number there is a corresponding real number, but 0% of real numbers > can be represented exactly by floating point numbers. It seems to me that there are a great many real numbers that can be represented exactly by floating point numbers. The number 1 is an example. I suppose that if you divide that count by the infinite count of all real numbers, you could argue that the result is 0%. -- http://mail.python.org/mailman/listinfo/python-list
Finding MIME type for a data stream
I'm pulling image data from a database blob, and serving it from a web2py app. I have to send the correct Content-Type header, so I need to detect the image type. Everything that I've found on the web so far, needs a file name on the disk, but I only have the data. It looks like the 'magic' package might be of use, but I can't find any documentation for it. Also, it seems like image/png works for other types of image data, while image/foo does not, yet I'm afraid that not every browser will play along as nicely. Thanks! Tobiah -- http://mail.python.org/mailman/listinfo/python-list
Re: Finding MIME type for a data stream
On 03/08/2012 02:11 PM, Dave Angel wrote: > On 03/08/2012 04:55 PM, Tobiah wrote: >> I'm pulling image data from a database blob, and serving >> it from a web2py app. I have to send the correct >> Content-Type header, so I need to detect the image type. >> >> Everything that I've found on the web so far, needs a file >> name on the disk, but I only have the data. >> >> It looks like the 'magic' package might be of use, but >> I can't find any documentation for it. >> >> Also, it seems like image/png works for other types >> of image data, while image/foo does not, yet I'm afraid >> that not every browser will play along as nicely. >> >> Thanks! >> >> Tobiah > > First step, ask the authors of the database what format of data this > blob is in. > > Failing that, write the same data locally as a binary file, and see what > application can open it. Or if you're on a Linux system, run file on > it. "file" can identify most data formats (not just images) just by > looking at the data. > > That assumes, of course, that there's any consistency in the data coming > out of the database. What happens if next time this blob is an Excel > spreadsheet? > I should simplify my question. Let's say I have a string that contains image data called 'mystring'. I want to do mime_type = some_magic(mystring) and get back 'image/jpg' or 'image/png' or whatever is appropriate for the image data. Thanks! Tobiah -- http://mail.python.org/mailman/listinfo/python-list
Re: Finding MIME type for a data stream
Also, I realize that I could write the data to a file and then use one of the modules that want a file path. I would prefer not to do that. Thanks -- http://mail.python.org/mailman/listinfo/python-list
Re: Finding MIME type for a data stream
> I have to assume you're talking python 2, since in python 3, strings > cannot generally contain image data. In python 2, characters are pretty > much interchangeable with bytes. Yeah, python 2 > if you're looking for a specific, small list of file formats, you could > make yourself a signature list. Most (not all) formats distinguish > themselves in the first few bytes. Yeah, maybe I'll just do that. I'm alowing users to paste images into a rich-text editor, so I'm pretty much looking at .png, .gif, or .jpg. Those should be pretty easy to distinguish by looking at the first few bytes. Pasting images may sound weird, but I'm using a jquery widget called cleditor that takes image data from the clipboard and replaces it with inline base64 data. The html from the editor ends up as an email, and the inline images cause the emails to be tossed in the spam folder for most people. So I'm parsing the emails, storing the image data, and replacing the inline images with an img tag that points to a web2py app that takes arguments that tell it which image to pull from the database. Now that I think of it, I could use php to detect the image type, and store that in the database. Not quite as clean, but that would work. Tobiah -- http://mail.python.org/mailman/listinfo/python-list
Re: Finding MIME type for a data stream
On 03/08/2012 06:12 PM, Irmen de Jong wrote: > On 8-3-2012 23:34, Tobiah wrote: >> Also, I realize that I could write the data to a file >> and then use one of the modules that want a file path. >> I would prefer not to do that. >> >> Thanks >> > > Use StringIO then, instead of a file on disk > > Irmen > Nice. Thanks. -- http://mail.python.org/mailman/listinfo/python-list
Re: Finding MIME type for a data stream
On 03/08/2012 06:04 PM, Dennis Lee Bieber wrote: > On Thu, 08 Mar 2012 15:40:13 -0800, Tobiah declaimed > the following in gmane.comp.python.general: > > >> Pasting images may sound weird, but I'm using a jquery >> widget called cleditor that takes image data from the >> clipboard and replaces it with inline base64 data. > > In Windows, I'd expect "device independent bitmap" to be the result > of a clipboard image... This jquery editor seems to detect the image data and translate it into an inline image like: http://mail.python.org/mailman/listinfo/python-list
Re: Finding MIME type for a data stream
> Something like the following might be worth a go: > (untested) > > from PIL import Image > img = Image.open(StringIO(blob)) > print img.format > This worked quite nicely. I didn't see a list of all returned formats though in the docs. The one image I had returned PNG So I'm doing: mime_type = "image/%s" % img.format.lower() I'm hoping that will work for any image type. Thanks, Tobiah -- http://mail.python.org/mailman/listinfo/python-list
Real time event accuracy
I'd like to send MIDI events from python to another program. I'd like advice as to how to accurately time the events. I'll have a list of floating point start times in seconds for the events, and I'd like to send them off as close to the correct time as possible. I'd also appreciate suggestions and pointers to a suitable python MIDI library, and maybe an outline of what must be done to get the MIDI events to the other program's MIDI in. Thanks, Tobiah -- http://mail.python.org/mailman/listinfo/python-list
Re: Real time event accuracy
> I don't think you can really do this accurately enough to get good > sound, but the basic mechanism is time.sleep(t) which takes a floating > point argument. That turns into the appropriate microsleep, I think. I think the time would have to come from a hardware clock. -- http://mail.python.org/mailman/listinfo/python-list
Hiding token information from users
I am making QR codes that cell phone users scan in order to make use of an application. Part of the information is a token that needs to be passed on to the server, but I'd rather not allow a person examining the QR code to be able to see that plain bit of information. I'd like to scramble up the token so that the result: 1) takes up the same (near, or less) number of characters as the original token. 2) They key can be derived from the input, and vise versa. 3) The result is alphanumeric. 4) When one character changes in the source, many characters are likely to change in the result. So if my token is: mytoken2011 The result might be something like: xm23ffz4uuw Then mytoken2012 might yield something very different: d8ru3jdhvhd I was thinking of just stringing up all letters and numbers into a 'wheel' and doing an 18 char rotation on the chars in the token, but that fails #4. The secret is not like the key to Fort Knox. We would rather not have the plain token out there, as it's internal business information, but we don't have to protect the information at all costs. Just making it really inconvenient to extract is fine. Thanks, Tobiah -- http://mail.python.org/mailman/listinfo/python-list
Re: Hiding token information from users
On 08/23/2011 08:08 AM, Ian Kelly wrote: How many of these codes do you need, and do they only need to be decrypted at a central server? You might be able to just create random strings of whatever form you want and associate them with the tokens in a database. Then they will be completely opaque. The tokens have a year portion that increments each year, and the base portion of the token will be created newly in accordance with new accounts that we take on. I really need some sort of algorithm that will let me take an unknown string and generate the encrypted bit on the fly. Thanks, Tobiah -- http://mail.python.org/mailman/listinfo/python-list
Re: Hiding token information from users
On 08/23/2011 09:55 AM, Steven D'Aprano wrote: Tobiah wrote: I really need some sort of algorithm that will let me take an unknown string and generate the encrypted bit on the fly. Google broken for you? *wink* I had some requirements in the OP that I could not find a solution for. Seriously, there are about a bazillion algorithms for encrypting and obfuscating strings. Depending on your security requirements, that can be as simple as rot13 and as complex as blowfish (or even more so). If it helps, I have a module that implements a selection of classical (i.e. insecure) encryption algorithms: http://pypi.python.org/pypi/obfuscate Earlier, you said: The secret is not like the key to Fort Knox. We would rather not have the plain token out there, as it's internal business information, but we don't have to protect the information at all costs. Just making it really inconvenient to extract is fine. I don't understand the point of this. What could your users do with the plain token that they shouldn't? I don't see why, if it's not worth encrypting properly, why it's worth obfuscating it at all. The token ends up translating into the name of a database on our server. With that information alone, it's difficult to imagine a serious vulnerability, yet we just thought it would be worth it to disguise the plain text. -- http://mail.python.org/mailman/listinfo/python-list
Re: is there any principle when writing python function
Furthermore: If you are moving code out of one function to ONLY be called by that ONE function then you are a bad programmer and should have your editor taken away for six months. You should ONLY create more func/methods if those func/methods will be called from two or more places in the code. The very essence of func/meths is the fact that they are reusable. While I understand and agree with that basic tenet, I think that the capitalized 'ONLY' is too strong. I do split out code into function for readability, even when the function will only be called from the place from which I split it out. I don't think that this adds to the 'spaghetti' factor. It can make my life much easier when I go to debug my own code years later. In python, I use a small function to block out an idea as a sort of pseudo code, although it's valid python. Then I just define the supporting functions, and the task is done: def validate_registrants(): for dude in get_registrants(): id = get_id(dude) amount_paid = get_amount_paid(dude) amount_owed = get_amount_owed(dude) if amount_paid != amount_owed(): flag(dude) I get that this cries out for a 'dude' object, but I'm just making a point. When I go back to this code, I can very quickly see what the overall flow is, and jump to the problem area by function name. The above block might expand to a couple of hundred lines if I didn't split it out like this. -- http://mail.python.org/mailman/listinfo/python-list
datetime.datetime and mysql different after python2.3
I'm grabbing two fields from a MySQLdb connection. One is a date type, and one is a time type. So I put the values in two variables and print them: import datetime date, time = get_fields() # for example print str(type(date)), str((type(time))) print str(date + time) In python 2.3.4, I get: 2010-07-06 09:20:45.00 Put in python2.4 and greater, I get this: 2010-07-06 So I'm having trouble adding the two to get one datetime. Thanks for any insight. Tobiah -- http://mail.python.org/mailman/listinfo/python-list
Re: datetime.datetime and mysql different after python2.3
> import datetime > date, time = get_fields() # for example > print str(type(date)), str((type(time))) > print str(date + time) News reader stripped newlines -- http://mail.python.org/mailman/listinfo/python-list
Midi output timing?
I'd like to use a python program to send out MIDI events to another program. I've done in the past by generating scores for csound which would do the MIDI output. The apparent hurdle is the timing bit. I've seen packages that allow the creation of MIDI events, but given a list of events of arbitrary start time, how can I schedule the triggering of each event? Csound runs in sync with the audio device output which is desirable if not necessary. Thanks -- https://mail.python.org/mailman/listinfo/python-list
Question about modules documentation
In this doc: https://docs.python.org/2/tutorial/modules.html Near the top it states: Modules can import other modules. It is customary but not required to place all import statements at the beginning of a module (or script, for that matter). The imported module names are placed in the importing module’s global symbol table. When it refers to 'the imported module names' it sounds as though it is referring to the top level variables and functions in the imported module. This is not the case as far as I can tell. If bar.py has a function bar() and in foo.py I do: import bar bar() of course this fails. I have to do: import bar bar.bar() I know it would work if I went: from bar import * bar() but that feature is only introduced in the next section of the doc. It seems that if the statement read: the imported module's name (singular) is placed in the importing module's global symbol table. That it would be more accurate. -- https://mail.python.org/mailman/listinfo/python-list
Re: Question about modules documentation
Re-reading I guess the plural refers to the multiple modules referenced in the first sentence. It was probably written that way before someone inserted the bit about the customary placement, which greatly clouds the connection. On 09/15/2017 09:03 AM, Tobiah wrote: > In this doc: > > https://docs.python.org/2/tutorial/modules.html > > Near the top it states: > > Modules can import other modules. It is customary but not > required to place all import statements at the beginning > of a module (or script, for that matter). The imported > module names are placed in the importing module’s global > symbol table. > > When it refers to 'the imported module names' it sounds as though > it is referring to the top level variables and functions in the > imported module. This is not the case as far as I can tell. > > > If bar.py has a function bar() and in foo.py I do: > > import bar > bar() > > of course this fails. I have to do: > > import bar > bar.bar() > > I know it would work if I went: > > from bar import * > bar() > > but that feature is only introduced in the next section > of the doc. > > It seems that if the statement read: > > the imported module's name (singular) is placed in the > importing module's global symbol table. > > That it would be more accurate. > > > > -- https://mail.python.org/mailman/listinfo/python-list
Re: Question about modules documentation
On 09/15/2017 09:25 AM, Stefan Ram wrote:> Tobiah writes: >> Modules can import other modules. It is customary but not >> required to place all import statements at the beginning >> of a module (or script, for that matter). The imported >> module names are placed > .. >> When it refers to 'the imported module names' it sounds as though >> it is referring to the top level variables and functions in the >> imported module. > >A "module name" usually is the name of a module. > >When someone uses "module name(s)" it does /not/ sound as >if he is using it to mean "the top level variables and >functions in the named module(s)". > >Since the preceding sentence uses the plural "import statements", >the next sentence has to use the plural "module names". > 'next sentence' is the operative piece. I think that if the bit about placement was moved to the end of the paragraph the whole thing would be more readable and I wouldn't have stumbled on it. -- https://mail.python.org/mailman/listinfo/python-list
Re: Question about modules documentation
>> 'next sentence' is the operative piece. I think that if the bit >> about placement was moved to the end of the paragraph the whole >> thing would be more readable and I wouldn't have stumbled on it. > > If it had meant "the imported module's names" or indeed "the imported > modules' names", I would hope it would have said so. > Fair enough. -- https://mail.python.org/mailman/listinfo/python-list
Assertions
Are these completely equivalent? def foo(thing): assert(thing > 0), "Thing must be greater than zero" def foo(thing): if not (thing > 0): raise AssertionError("Thing must be greater than zero") Other than the fact that the assertion can be turned off with -O? Thanks, Tobiah -- https://mail.python.org/mailman/listinfo/python-list
Creating a MIDI file
What would be the best library to use for creating MIDI files that I could import into a DAW like Reaper? Thanks, Tobiah -- https://mail.python.org/mailman/listinfo/python-list
Sequence MIDI events from python.
I know that there are a few good MIDI libraries out there. The examples that I've seen for real-time triggering of events rely on a sleep function to realize the timing. This is not accurate or precise enough for musical applications. What options do I have if I want to write a MIDI sequencer in python? I imagine I'd have to sync to an audio device to get the timing right. Thank for any help. Tobiah -- https://mail.python.org/mailman/listinfo/python-list
Re: Sequence MIDI events from python. (Posting On Python-List Prohibited)
On 10/26/2017 4:30 PM, Lawrence D’Oliveiro wrote: On Friday, October 27, 2017 at 12:02:40 PM UTC+13, Tobiah wrote: I know that there are a few good MIDI libraries out there. The examples that I've seen for real-time triggering of events rely on a sleep function to realize the timing. This is not accurate or precise enough for musical applications. Why not look at the source code of the “good” ones? No get. zample plez. -- https://mail.python.org/mailman/listinfo/python-list
MySQLdb and conn.select_db()
I have an older Ubuntu machine, 8.04 that errors when I try to do conn.select_db(). AttributeError: 'Connection' object has no attribute 'select_db' My 16.4 box acts as I'd expect. Did this get added at some point? I'd really like to be able to get generic links so I can do things like "show databases" and then maybe select_db() after that. It's also handy to be able to change databases on the fly for things like looking at the table set in multiple databases. The main docs that I can find only show select_db() under the _mysql library, yet my new machine is supporting it from the MySQLdb library. Are the docs lagging? Can I download the 'better' MySQLdb package and install it on the 8.04 machine? Thanks, Tobiah -- https://mail.python.org/mailman/listinfo/python-list
Re: Changing calling sequence
On 5/11/22 06:33, Michael F. Stemper wrote: I have a function that I use to retrieve daily data from a home-brew database. Its calling sequence is; def TempsOneDay( year, month, date ): After using it (and its friends) for a few years, I've come to realize that there are times where it would be advantageous to invoke it with a datetime.date as its single argument. You could just use all keyword args: def TempsOneDay(**kwargs): if 'date' in kwargs: handle_datetime(kwargs['date']) elif 'year' in kwargs and 'month' in kwargs and 'day' in kwargs: handle_args(kwargs['year'], kwargs['month'], kwargs['day']) else: raise Exception("Bad keyword args") TempsOneDay(date=datetime.datetime.now) TempsOneDay(year=2022, month=11, day=30) -- https://mail.python.org/mailman/listinfo/python-list
Re: Which linux distro is more conducive for learning the Python programming language?
On 8/3/22 19:01, Turritopsis Dohrnii Teo En Ming wrote: Subject: Which linux distro is more conducive for learning the Python programming language? You might try Pythontu. Not really. Get the distro that looks appealing to you. One won't be better than the other with regard to learning python. Good day from Singapore, May I know which linux distro is more conducive for learning the Python programming language? Since I have absolutely and totally FREE RHEL developer subscription (I don't need to spend a single cent), can I use Red Hat Enterprise Linux version 9.0 to learn Python? Is it the most popular linux distro for learning Python? I just want to know which linux distro and version is more conducive for learning Python. Because there are thousands of linux distros out there. And I just want to settle down on a particular linux distro and version. Thank you. Regards, Mr. Turritopsis Dohrnii Teo En Ming Targeted Individual in Singapore 4 Aug 2022 Thursday Blogs: https://tdtemcerts.blogspot.com https://tdtemcerts.wordpress.com -- https://mail.python.org/mailman/listinfo/python-list
UTF-8 and latin1
I get data from various sources; client emails, spreadsheets, and data from web applications. I find that I can do some_string.decode('latin1') to get unicode that I can use with xlsxwriter, or put in the header of a web page to display European characters correctly. But normally UTF-8 is recommended as the encoding to use today. latin1 works correctly more often when I am using data from the wild. It's frustrating that I have to play a guessing game to figure out how to use incoming text. I'm just wondering if there are any thoughts. What if we just globally decided to use utf-8? Could that ever happen? -- https://mail.python.org/mailman/listinfo/python-list
Re: UTF-8 and latin1
On 8/17/22 08:33, Stefan Ram wrote: Tobiah writes: I get data from various sources; client emails, spreadsheets, and data from web applications. I find that I can do some_string.decode('latin1') Strings have no "decode" method. ("bytes" objects do.) I'm using 2.7. Maybe that's why. Toby -- https://mail.python.org/mailman/listinfo/python-list
Re: UTF-8 and latin1
That has already been decided, as much as it ever can be. UTF-8 is essentially always the correct encoding to use on output, and almost always the correct encoding to assume on input absent any explicit indication of another encoding. (e.g. the HTML "standard" says that all HTML files must be UTF-8.) I got an email from a client with blast text that was in French with stuff like: Montréal, Quebéc. latin1 did the trick. Also, whenever I get a spreadsheet from a client and save as .csv, or take browser data through PHP, it always seems to work with latin1, but not UTF-8. -- https://mail.python.org/mailman/listinfo/python-list
Re: UTF-8 and latin1
Generally speaking browser submisisons were/are supposed to be sent using the same encoding as the page, so if you're sending the page as "latin1" then you'll see that a fair amount I should think. If you send it as "utf-8" then you'll get 100% utf-8 back. The only trick I know is to use . Would that 'send' the post as utf-8? I always expected it had more to do with the way the user entered the characters. How do they by the way, enter things like Montréal, Quebéc. When they enter that into a text box on a web page can we say it's in a particular encoding at that time? At submit time? -- https://mail.python.org/mailman/listinfo/python-list
Re: UTF-8 and latin1
You configure the web server to send: Content-Type: text/html; charset=... in the HTTP header when it serves HTML files. So how does this break down? When a person enters Montréal, Quebéc into a form field, what are they doing on the keyboard to make that happen? As the string sits there in the text box, is it latin1, or utf-8 or something else? How does the browser know what sort of data it has in that text box? -- https://mail.python.org/mailman/listinfo/python-list
Re: Passing information between modules
On 11/18/22 02:53, Stefan Ram wrote: Can I use "sys.argv" to pass information between modules as follows? in module A: import sys sys.argv.append( "Hi there!" ) in module B: import sys message = sys.argv[ -1 ] Kind of seems like a code smell. I think you would normally just inject the dependencies like: module_b.do_thing("Hi there!") If you really want to have a module-global space, you could just create a module globals.py, and import that in every module that needs to share globals. You can just do globals.message = "Hi there!" and from another module do print globals.message. -- https://mail.python.org/mailman/listinfo/python-list
Re: ok, I feel stupid, but there must be a better way than this! (finding name of unique key in dict)
On 1/20/23 07:29, Dino wrote: let's say I have this list of nested dicts: [ { "some_key": {'a':1, 'b':2}}, { "some_other_key": {'a':3, 'b':4}} ] I need to turn this into: [ { "value": "some_key", 'a':1, 'b':2}, { "value": "some_other_key", 'a':3, 'b':4} ] This doesn't look like the program output you're getting. -- https://mail.python.org/mailman/listinfo/python-list
Re: Log File
On 5/31/23 00:22, ahsan iqbal wrote: Why we need a log file ? If i read a large text file than how log file help me in this regard? If you were parsing each line of this text file looking for information, perhaps some of the lines would not be formatted correctly, and you would be unable to get the information from those lines. Maybe you would like to write those bad lines to a log file so that you could analyze them later. -- https://mail.python.org/mailman/listinfo/python-list
Pandas or Numpy
I know very little about either. I need to handle score input files for Csound. Each line is a list of floating point values where each column has a particular meaning to the program. I need to compose large (hundreds, thousands, maybe millions) lists and be able to do math on, or possibly sort by various columns, among other operations. A common requirement would be to do the same math operation on each value in a column, or redistribute the values according to an exponential curve, etc. One wrinkle is that the first column of a Csound score is actually a single character. I was thinking if the data types all had to be the same, then I'd make a translation table or just use the ascii value of the character, but if I could mix types that might be a smidge better. It seems like both libraries are possible choices. Would one be the obvious choice for me? Thanks! -- https://mail.python.org/mailman/listinfo/python-list
Re: How to test input via subprocess.Popen with data from file
Why not just have scripts that echo out the various sets of test data you are interested in? That way, Popen would always be your interface and you wouldn't have to make two cases in the consumer script. In other words, make program that outputs test data just like your main data source program. Then the consumer would only have to work in one way. On 3/10/22 04:16, Loris Bennett wrote: Hi, I have a command which produces output like the following: Job ID: 9431211 Cluster: curta User/Group: build/staff State: COMPLETED (exit code 0) Nodes: 1 Cores per node: 8 CPU Utilized: 01:30:53 CPU Efficiency: 83.63% of 01:48:40 core-walltime Job Wall-clock time: 00:13:35 Memory Utilized: 6.45 GB Memory Efficiency: 80.68% of 8.00 GB I want to parse this and am using subprocess.Popen and accessing the contents via Popen.stdout. However, for testing purposes I want to save various possible outputs of the command as text files and use those as inputs. What format should I use to pass data to the actual parsing function? I could in both production and test convert the entire input to a string and pass the string to the parsing method. However, I could use something like test_input_01 = subprocess.Popen( ["cat test_input_01.txt"], stdout=subprocess.PIPE, ) for the test input and then pass a Popen object to the parsing function. Any comments on these alternative or suggestions for doing something completely different? Cheers, Loris -- https://mail.python.org/mailman/listinfo/python-list
importing down in code rather than at top of file.
Is it worth while to defer the import of a large module that seldom gets used in the script? import sys import os if hardly_ever_happens(): import large_module large_module.do_task() I imagine it takes a certain amount of processing power and memory to import a module, so it seems like I'd save those resources with the above pattern. The down side would be that it's nice to see all of the imports at the top which would follow convention. Should I care? Tobiah -- https://mail.python.org/mailman/listinfo/python-list
Putting Unicode characters in JSON
I have some mailing information in a Mysql database that has characters from various other countries. The table says that it's using latin-1 encoding. I want to send this data out as JSON. So I'm just taking each datum and doing 'name'.decode('latin-1') and adding the resulting Unicode value right into my JSON structure before doing .dumps() on it. This seems to work, and I can consume the JSON with another program and when I print values, they look nice with the special characters and all. I was reading though, that JSON files must be encoded with UTF-8. So should I be doing string.decode('latin-1').encode('utf-8')? Or does the json module do that for me when I give it a unicode object? Thanks -- https://mail.python.org/mailman/listinfo/python-list
Re: Putting Unicode characters in JSON
On 03/22/2018 01:09 PM, Chris Angelico wrote: On Fri, Mar 23, 2018 at 6:46 AM, Tobiah wrote: I have some mailing information in a Mysql database that has characters from various other countries. The table says that it's using latin-1 encoding. I want to send this data out as JSON. So I'm just taking each datum and doing 'name'.decode('latin-1') and adding the resulting Unicode value right into my JSON structure before doing .dumps() on it. This seems to work, and I can consume the JSON with another program and when I print values, they look nice with the special characters and all. I was reading though, that JSON files must be encoded with UTF-8. So should I be doing string.decode('latin-1').encode('utf-8')? Or does the json module do that for me when I give it a unicode object? Reconfigure your MySQL database to use UTF-8. There is no reason to use Latin-1 in the database. If that isn't an option, make sure your JSON files are pure ASCII, which is the common subset of UTF-8 and Latin-1. ChrisA It works the way I'm doing it. I checked and it turns out that whether I do datum.decode('latin-1') or datum.decode('latin-1').encode('utf8') I get identical JSON files after .dumps(). -- https://mail.python.org/mailman/listinfo/python-list
Re: Putting Unicode characters in JSON
On 03/22/2018 12:46 PM, Tobiah wrote: I have some mailing information in a Mysql database that has characters from various other countries. The table says that it's using latin-1 encoding. I want to send this data out as JSON. So I'm just taking each datum and doing 'name'.decode('latin-1') and adding the resulting Unicode value right into my JSON structure before doing .dumps() on it. This seems to work, and I can consume the JSON with another program and when I print values, they look nice with the special characters and all. I was reading though, that JSON files must be encoded with UTF-8. So should I be doing string.decode('latin-1').encode('utf-8')? Or does the json module do that for me when I give it a unicode object? Thanks for all the discussion. A little more about our setup: We have used a LAMP stack system for almost 20 years to deploy hundreds of websites. The database tables are latin-1 only because at the time we didn't know how or care to change it. More and more, 'special' characters caused a problem. They would not come out correctly in a .csv file or wouldn't print correctly. Lately, I noticed that a JSON file I was sending out was delivering unreadable characters. That's when I started to look into Unicode a bit more. From the discussion, and my own guesses, it looks as though all have to do is string.decode('latin-1'), and stuff that Unicode object right into my structure that gets handed to json.dumps(). If I changed my database tables to all be UTF-8 would this work cleanly without any decoding? Whatever people are doing to get these characters in, whether it's foreign keyboards, or fancy escape sequences in the web forms, would their intended characters still go into the UTF-8 database as the proper characters? Or now do I have to do a conversion on the way in to the database? We also get import data that often comes in .xlsx format. What encoding do I get when I dump a .csv from that? Do I have to ask the sender? I already know that they don't know. Toby -- https://mail.python.org/mailman/listinfo/python-list
Re: ***URGENT CONTRACT OPPORTUNITY***
On 03/28/2018 06:45 AM, cagdenw...@gmail.com wrote: opportunity in Tours, France starting ASAP!!! and able to start ASAP!!! contact me ASAP When should I apply? -- https://mail.python.org/mailman/listinfo/python-list
Re: semicolon at end of python's statements
On 04/01/2018 11:31 PM, dlt.joaq...@gmail.com wrote: El miércoles, 28 de agosto de 2013, 21:18:26 (UTC-3), Mohsen Pahlevanzadeh escribió: Dear all, I'm C++ programmer and unfortunately put semicolon at end of my statements in python. Quesion: What's really defferences between putting semicolon and don't put? Yours, Mohsen Well, if you have to program in both c and python, and switch between them on intervals of time lowers than some hours I would suggest keep on with the semicolons at the end of lines... It would be very difficult to lose that habit, and while it is inoffensive on python, it may cause some troubles on c. I don't know. It's not Pep 8, or at least pycharm complains about it. I'd hate to inherit the semicolon riddled code. I switch between python and PHP twenty or so times a day since we use both at work. Once in a while I throw in a rogue semicolon, but it's not often enough to cause a bother. -- https://mail.python.org/mailman/listinfo/python-list
Re: semicolon at end of python's statements
On 04/03/2018 09:48 AM, kar...@gmail.com wrote: Semicolon is optional. If you put a semicolon at the end of the of a statement, you can keep writing statements. a=3;b=2 PyCharm still complains about two statements on one line and sites Pep 8. I never used to pay much attention to Pep 8, but PyCharm has greatly eroded my resistance. -- https://mail.python.org/mailman/listinfo/python-list
syntax oddities
Why is it len(object) instead of object.len? Why is it getattr(object, item) rather then object.getattr(item)? etc... Thanks -- https://mail.python.org/mailman/listinfo/python-list
Re: what does := means simply?
On 05/16/2018 08:54 PM, Steven D'Aprano wrote: On Thu, 17 May 2018 05:33:38 +0400, Abdur-Rahmaan Janhangeer wrote: what does := proposes to do? Simply, it proposes to add a new operator := for assignment (or binding) as an expression, as an addition to the = assignment operator which operates only as a statement. The syntax is: name := expression and the meaning is: 1. evaluate 2. assign that value to 3. return that same value as the result Well, that would be a welcome addition! -- https://mail.python.org/mailman/listinfo/python-list
Re: syntax oddities
Top posting is awesome for the reader plowing through a thread in order. In that case the cruft at the bottom is only for occasional reference. Ok, I yield! I know the bottom-posting party has congress right now. On 05/17/2018 06:29 AM, Grant Edwards wrote: On 2018-05-17, Abdur-Rahmaan Janhangeer wrote: just a remark that people help and discuss on more issues unrelated to python [...] On Thu, 17 May 2018, 07:45 Steven D'Aprano, < steve+comp.lang.pyt...@pearwood.info> wrote: On Thu, 17 May 2018 05:25:44 +0400, Abdur-Rahmaan Janhangeer wrote: And one such popular issue is how top-posting is evil. -- https://mail.python.org/mailman/listinfo/python-list
Re: why does list's .remove() does not return an object?
On 05/17/2018 09:25 AM, Ned Batchelder wrote: On 5/17/18 11:57 AM, Abdur-Rahmaan Janhangeer wrote: x = [0,1] x.remove(0) new_list = x Just call the original list 'new_list' to begin with. new_list = [0, 1] new_list.remove(0) There you are! -- https://mail.python.org/mailman/listinfo/python-list
Undocumented unescape() method in HTMLParser?
I came across its usage in StackOverflow somewhere, but didn't see it in the docs. I'm using 2.7. I needed it while writing a class for generating text documents out of HTML documents for attaching to emails, which lowers spam scores. I lifted the basis for this from the top answer here: https://tinyurl.com/yb92x8ra While not complete, I thought it might be of interest. Improvements welcome: # from HTMLParser import HTMLParser def main(): parser = TextExtractor() html = ''' head "Hi there!" some javascript class{style} Print this''' print parser.strip_tags(html) class TextExtractor(HTMLParser): def __init__(self): HTMLParser.__init__(self) self.silent_tag = None self.fed = [] self.silent_tags = ['head', 'script', 'style'] def handle_starttag(self, tag, atts): if tag in self.silent_tags: self.silent_tag = tag def handle_endtag(self, tag): if tag == self.silent_tag: self.silent_tag = None def handle_data(self, d): if not self.silent_tag: self.fed.append(d) def handle_entityref(self, name): self.fed.append(self.unescape("&%s;" % name)) def get_data(self): return ''.join(self.fed) def strip_tags(self, html): self.feed(html) data = self.get_data() self.fed = [] self.reset() return data main() # Output: "Hi there!" Print this Toby -- https://mail.python.org/mailman/listinfo/python-list
Sorting and spaces.
I had a case today where I needed to sort two string: ['Awards', 'Award Winners'] I consulted a few sources to get a suggestion as to what would be correct. My first idea was to throw them through a Linux command line sort: Awards Award Winners Then I did some Googling, and found that most US systems seem to prefer that one ignore spaces when alphabetizing. The sort program seemed to agree. I put the items into the database that way, but I had forgotten that my applications used python to sort them anyway. The result was different: >>> a = ['Awards', 'Award Winners'] >>> sorted(a) ['Award Winners', 'Awards'] So python evaluated the space as a lower ASCII value. Thoughts? Are there separate tools for alphabetizing rather then sorting? Thanks, Tobiah -- https://mail.python.org/mailman/listinfo/python-list
Checking whether type is None
Consider: >>> type({}) is dict True >>> type(3) is int True >>> type(None) is None False Obvious I guess, since the type object is not None. So what would I compare type(None) to? >>> type(None) >>> type(None) is NoneType Traceback (most recent call last): File "", line 1, in NameError: name 'NoneType' is not defined I know I ask whether: >>> thing is None but I wanted a generic test. I'm trying to get away from things like: >>> type(thing) is type(None) because of something I read somewhere preferring my original test method. Thanks -- https://mail.python.org/mailman/listinfo/python-list
MIDI note timing
I'd like to do some algorithmic composing using python. I've seen various libraries that seem to be capable of sending a MIDI message to a MIDI port, but I don't know where to get the timing from. Normally, with something like CSOUND, the program locks itself to the timing of the soundcard and presumably uses that for timing. Is there anything for python that could do this? I've seen rather ridiculous examples using sleeps for timing, but for musical applications the timing really needs to come form a hardware soundcard, especially as I'd like to play audio through the card at the same time and have it line up perfectly with the MIDI. Thanks for any suggestions. Toby -- https://mail.python.org/mailman/listinfo/python-list
@staticmethod or def function()?
My IDE (pycharm) suggests that I mark my class methods with @staticmethod when they don't use 'self'. Sounds good. I did that then it suggested I had the option to make a regular function instead, at the file level. That's a possibility. I was thinking that I'd leave the method in the class unless it was ever also used by another class. What do you think? -- https://mail.python.org/mailman/listinfo/python-list
Re: Are all items in list the same?
On 1/8/19 9:20 AM, Alister wrote: On Tue, 08 Jan 2019 17:15:17 +, Alister wrote: On Tue, 08 Jan 2019 16:48:58 +0200, Serhiy Storchaka wrote: 08.01.19 11:07, Peter Otten пише: Bob van der Poel wrote: I need to see if all the items in my list are the same. I was using set() for this, but that doesn't work if items are themselves lists. So, assuming that a is a list of some things, the best I've been able to come up with it: if a.count( targ ) == len(a): I'm somewhat afraid that this won't scale all that well. Am I missing something? a[1:] == a[:-1] :) Very clever! It is definitely the shortest solution. would that still not return true if the list was a palindrome? ignore me, just tried & ok You were right the first time. The above comparison should have been a == a[::-1] A palindrome will pass. -- https://mail.python.org/mailman/listinfo/python-list
Email blast management?
I'm tasked with adding the ability for users of a website to send bulk emails out to their customers. Before I write it all from scratch, are there any good tools that will allow me to provide: * A place to compose their email, with images and links * A way to manage their list of recipients Perhaps most important: * A way to verify emails, track (as much as possible) receipt of the email, and track bounce-backs, click-throughs, etc. The solution could be anywhere from close to an entire solution, like some free, light CRM package, down to recommendations on some good supporting libraries that will help me with any of these tasks. Thanks, Tobiah -- https://mail.python.org/mailman/listinfo/python-list
Re: How to pass username and password in the curl requests using requests python module
On 5/2/19 4:30 AM, Pradeep Patra wrote: Can anyone pls help in this regard? Something like this?: requests.get('https://api.github.com/user', auth=('user', 'pass')) -- https://mail.python.org/mailman/listinfo/python-list
Handle foreign character web input
A guy comes in and enters his last name as RÖnngren. So what did the browser really give me; is it encoded in some way, like latin-1? Does it depend on whether the name was cut and pasted from a Word doc. etc? Should I handle these internally as unicode? Right now my database tables are latin-1 and things seem to usually work, but not always. Also, what do people do when searching for a record. Is there some way to get 'Ronngren' to match the other possible foreign spellings? -- https://mail.python.org/mailman/listinfo/python-list
Re: Handle foreign character web input
On 6/28/19 1:33 PM, Chris Angelico wrote:> On Sat, Jun 29, 2019 at 6:31 AM Tobiah wrote: A guy comes in and enters his last name as RÖnngren. So what did the browser really give me; is it encoded in some way, like latin-1? Does it depend on whether the name was cut and pasted from a Word doc. etc? Should I handle these internally as unicode? Right now my database tables are latin-1 and things seem to usually work, but not always. Definitely handle them as Unicode. You'll receive them in some encoding, probably UTF-8, and it depends on the browser. Ideally, your back-end library (eg Flask) will deal with that for you. It varies by browser? So these records are coming in from all over the world. How do people handle possibly assorted encodings that may come in? I'm using Web2py. Does the request come in with an encoding built in? Is that how people get the proper unicode object? Also, what do people do when searching for a record. Is there some way to get 'Ronngren' to match the other possible foreign spellings? Ehh... probably not. That's a human problem, not a programming one. Best of luck. Well so I'm at an event. A guy comes up to me at the kiosk and say his name is RÖnngren. I can't find him, typing in "ron" so I ask him how to spell his last name. What does he say, and what do I type? -- https://mail.python.org/mailman/listinfo/python-list
itertools cycle() docs question
In the docs for itertools.cycle() there is a bit of equivalent code given: def cycle(iterable): # cycle('ABCD') --> A B C D A B C D A B C D ... saved = [] for element in iterable: yield element saved.append(element) while saved: for element in saved: yield element Is that really how it works? Why make the copy of the elements? This seems to be equivalent: def cycle(iterable): while iterable: for thing in iterable: yield thing -- https://mail.python.org/mailman/listinfo/python-list
Re: itertools cycle() docs question
On 8/21/19 11:38 AM, Rob Gaddi wrote: On 8/21/19 11:27 AM, Tobiah wrote: In the docs for itertools.cycle() there is a bit of equivalent code given: def cycle(iterable): # cycle('ABCD') --> A B C D A B C D A B C D ... saved = [] for element in iterable: yield element saved.append(element) while saved: for element in saved: yield element Is that really how it works? Why make the copy of the elements? This seems to be equivalent: def cycle(iterable): while iterable: for thing in iterable: yield thing You assume that the initial iterable is reusable. If its not, the only way you can go back to the beginning is to have kept track of it yourself. I see. What is an example of an iterable that is not reusable? -- https://mail.python.org/mailman/listinfo/python-list
Re: How to remove a string from a txt file?
On 9/4/19 8:08 AM, Spencer Du wrote: Hi I want to remove a string from a txt file and then print out what I have removed. How do I do this. The txt file is in this format and should be kept in this format. txt.txt: laser,cameras, Thanks Do you want to remove one of the fields by using an argument? Like: my_py_solution txt.txt cameras Its not clear what you are trying to achieve. -- https://mail.python.org/mailman/listinfo/python-list
[OT(?)] Ubuntu 18 now defaults to 4-space tabs
We upgraded a server to 18.04 and now when I start typing a python file (seems to be triggered by the .py extension) the tabs default to 4 spaces. We have decades of code that use tab characters, and it has not been our intention to change that. I found a /usr/share/vim/vim80/indent/python.vim and tried moving it out of the way, but the behavior was still there. This is more of a vim question perhaps, but I'm already subscribed here and I figured someone would know what to do. Thanks! -- https://mail.python.org/mailman/listinfo/python-list
Re: [OT(?)] Ubuntu 18 vim now defaults to 4-space tabs
Your subject missed a critical word: vim. It's there! Run vim. Then ':set' to see what's set different than default. Then, if it is tabstop you want to know about, ':verbose set tabstop?' will tell you where that setting was last altered. Nothing that seems to point to space indent: background=dark hlsearchruler smartcase ttyfast wildmenu helplang=C. ignorecase scroll=36 smartindent ttymouse=xterm2 nowrap hidden modifiedshowcmd nostartofline wildcharm=^Z I'll check with a vim specific group. Thanks! Toby -- https://mail.python.org/mailman/listinfo/python-list
Re: [OT(?)] Ubuntu 18 vim now defaults to 4-space tabs
Since it does not appear to have "filetype=python" in there, maybe I should have specified "Run vim with a .py filename". Yes, that was a bit that took me a while to figure out! So I used your trick and did: :verbose set shiftwidth? and it revealed: cd /usr/share/vim/vim80/ftplugin And in that file I fount the clause: if !exists("g:python_recommended_style") || g:python_recommended_style != 0 " As suggested by PEP8. setlocal expandtab shiftwidth=4 softtabstop=4 tabstop=8 endif So there it is. I put let g:python_recommended_style = 0 in my ~/.vimrc and my problem was elegantly solved. I continued here with the answer so that those that find my original post by Googling the same question would not be left hanging. Tobiah -- https://mail.python.org/mailman/listinfo/python-list
Delay in python startup.
I don't have a lot of information, so here goes a shot in the dark. One day I started experiencing a delay when starting python. I'm on Ubuntu 16.04. It takes three seconds to get a prompt when I type 'python' on the command line (Python 2.7.12). When I run a script that imports packages, it takes longer, up to 17 seconds just to do the imports. Python3 is not affected, and is snappy as expected. That's all I know. I'm hoping someone else has seen this. I'm about ready to wipe the drive and upgrade to 18.04. -- https://mail.python.org/mailman/listinfo/python-list
Re: Hi how do I import files inside a txt file?
On 9/2/19 3:32 AM, Spencer Du wrote: Hi How do i import files inside a txt file if they exist in the current directory? Once you've read the module names you can use: new_module = __import__(modulename) So you'd read the name from your file into modulename and import the name contained in that variable in this way. -- https://mail.python.org/mailman/listinfo/python-list
Re: Delay in python startup.
On 9/30/19 9:54 AM, Chris Angelico wrote: On Tue, Oct 1, 2019 at 1:56 AM Tobiah wrote: I don't have a lot of information, so here goes a shot in the dark. One day I started experiencing a delay when starting python. I'm on Ubuntu 16.04. It takes three seconds to get a prompt when I type 'python' on the command line (Python 2.7.12). When I run a script that imports packages, it takes longer, up to 17 seconds just to do the imports. Python3 is not affected, and is snappy as expected. That's all I know. I'm hoping someone else has seen this. I'm about ready to wipe the drive and upgrade to 18.04. Python 2 and Python 3 have completely independent installations, so it could be a lot of things. First question: Does it take three seconds *every* time you type 'python', or only the first time? If it's slow the first time but then fast, it's probably just a matter of disk caching; running Python 3 doesn't pre-cache the files for Python 2, so you have to pay the load-time cost anew. If it's slow every time, though, you may have something messing with your startup. Try "python -S" and "python -E" see if they're just as slow. That would be a way to delve into things a bit. ChrisA It was much faster with -S and instantaneous with -E. I had a directory in my PYTHONPATH that I mount with sshfs from a server. For some reason that mount is very slow. Thanks for helping me figure this out. Tobiah -- https://mail.python.org/mailman/listinfo/python-list
Odd delays when cwd is on a network mount
I have a directory mounted with sshfs over a 5mb connection. It's quite usable under most circumstances. When I run python from a directory under that mount, imports from local directories are quite slow: $ python2.7 import my_module ## takes 25 seconds to complete my_module.__file__ /local/dir/not/on/mount/my_module.py When I do the same thing from my home directory there is no delay. $ wc -l /local/dir/not/on/mount/my_module.py 156 /local/dir/not/on/mount/my_module.py Thanks for any help. Tobiah -- https://mail.python.org/mailman/listinfo/python-list
Re: Odd delays when cwd is on a network mount
On 10/11/19 10:56 AM, Tobiah wrote: I have a directory mounted with sshfs over a 5mb connection. It's quite usable under most circumstances. When I run python from a directory under that mount, imports from local directories are quite slow: $ python2.7 import my_module ## takes 25 seconds to complete my_module.__file__ /local/dir/not/on/mount/my_module.py When I do the same thing from my home directory there is no delay. $ wc -l /local/dir/not/on/mount/my_module.py 156 /local/dir/not/on/mount/my_module.py Thanks for any help. Tobiah Another way: $ cd ~ $ python2.7 import os os.chdir('/remote/mount/point') import my_module## 25 seconds again my_module.__file__ /local/dir/not/on/mount/my_module.py Without the os.chdir() the import is instantaneous. -- https://mail.python.org/mailman/listinfo/python-list
Re: Odd delays when cwd is on a network mount
On 10/11/19 6:04 PM, Gregory Ewing wrote: Cameron Simpson wrote: Python's default sys.path includes the current working directory. Only in an interactive session, where it usually makes sense. I was only using the REPL for demonstration. The same delay happens when I import a module in a script. The module file is on the local drive. I only have to have a CWD on the mounted drive to experience the 25 second delay. As I said, the mount is over a 5mb connection - it's not wildly quick but it's quite usable normally. -- https://mail.python.org/mailman/listinfo/python-list
Re: 3rd party mail package
On 12/18/19 9:27 AM, Tobiah wrote: On 12/14/19 1:13 AM, Barry wrote: I guess the 2nd party is the user. I think of the user as the first party. 1) I want a thing for python. 2) Python doesn't have a very good one 3) Someone else will give it to you Wikipedia disagrees with me: https://en.wikipedia.org/wiki/Third-party_source -- https://mail.python.org/mailman/listinfo/python-list
Re: 3rd party mail package
On 12/14/19 1:13 AM, Barry wrote: I guess the 2nd party is the user. I think of the user as the first party. 1) I want a thing for python. 2) Python doesn't have a very good one 3) Someone else will give it to you Barry On 13 Dec 2019, at 21:13, Abdur-Rahmaan Janhangeer wrote: Wonder where the 2nd party went to. Thanks will look into it! -- https://mail.python.org/mailman/listinfo/python-list -- https://mail.python.org/mailman/listinfo/python-list
Re: strptime for different languages
What I tried is a cascade of try's: try: d = strptime(date_string, format_string_1) except: try: d = strptime(date_string, format_string_2) except: try: d = strptime(date_string, format_string_3) except: ... This is not about dates, but for the above, I'd try: for f in (format1, format2, format3): try: d = strptime(date_string, f) except: continue else: break That way you can manipulate the content and number of the formats, or pull them from a database or whatever without having to edit your code in a messy way. Tobiah -- https://mail.python.org/mailman/listinfo/python-list
Re: 3rd party mail package
I think of the user as the first party But that is not what Wikipedia article you linked says. “ In commerce, a "third-party source" means a supplier (or service provider) who is not directly controlled by either the seller (first party) nor the customer/buyer (second party) in a business transaction.” I know. I admitted that the Wikipedia article disagreed with me, forcing me into a retraction of my previous assertion. I didn't post that link to reinforce my original argument. Tobiah -- https://mail.python.org/mailman/listinfo/python-list
Re: strptime for different languages
A couple of point about your code: 1. Don't use a bare 'except' because it'll catch _any_ exception. See what exception strptime will raise and catch only that. I'm well aware of this, but I was too lazy to write something to generate the exception to find out what datetime would throw in this case. It crossed my mind when posting, but I was illustrating an idea rather than submitting usable code. 2. Why use 'continue' instead of 'pass'? No reason. Does one have a benefit over the other? Tobiah -- https://mail.python.org/mailman/listinfo/python-list
Re: Font size
from random import randint rand = randint(0,36) print rand Don't forget about the double zero slot. Tobiah -- http://mail.python.org/mailman/listinfo/python-list
Defining __getitem__() in a class that inherits from (dict)
#!/usr/bin/python # Hi, # # I noticed something interesting when trying to define # the __getitem__() method in a class that inherits from # (dict). If within the __getitem__ method I attempt # to get an item from self, the __getitem__ method is # called in an infinite recursion. I am very fond of # inheriting from (dict) as in the class 'bar' below, # but this problem is making me think that I will have # to write them as in 'foo' below. Is there a workaround # to make the class 'bar' work as I planned? class foo: data = {} def __getitem__(self, what): if not self.data.has_key(what): self.data[what] = None return None else: return self.data[what] class bar(dict): data = {} def __getitem__(self, what): if not self.has_key(what): self[what] = None return None else: return self[what] f = foo() b = bar() print f['somekey'] print f['somekey'] print b['somekey'] print b['somekey'] # OUTPUT: # None # None # None # Traceback (most recent call last): # File "", line 47, in ? # File "", line 36, in __getitem__ # File "", line 36, in __getitem__ # File "", line 36, in __getitem__ Thanks, Tobiah -- http://mail.python.org/mailman/listinfo/python-list
Re: Defining __getitem__() in a class that inherits from (dict)
My appreciation for your responses is not easily imparted through text. Thank You. Steven Bethard wrote: Michael Hoffman wrote: Tobiah wrote: If within the __getitem__ method I attempt to get an item from self, the __getitem__ method is called in an infinite recursion. You need to explicitly use dict.__getitem__(self, key) instead of using self[key] directly. or super(bar, self).__getitem__(key) STeVe -- http://mail.python.org/mailman/listinfo/python-list
Second argument to super().
What is the purpose of the second argument to super()? What is meant by the returning of an 'unbound' object when the argument is omitted. Also, when would I pass an object as the second argument, and when would I pass a type? Thanks, Tobiah -- http://mail.python.org/mailman/listinfo/python-list
Re: os.walk(entire filesystem)
When I do os.walk('/') on a Linux computer, the entire file system is walked. On windows, however, I can only walk one drive at a time (C:\, D:\, etc.). If this is a personal utility for one computer, and if you run XP on that computer, then you have the ability to mount secondary drives on to the file system of your main drive. This would give you the effect that you are enjoying on the Linux side. I am guessing that the utility that does this is the same one that allows you to partition drives, but I'm not sure. -- http://mail.python.org/mailman/listinfo/python-list
How can I load a module when I will only know the name 'on the fly'
m = get_next_module() some_nice_function_somehow_loads( m ) Thanks, Tobiah -- http://mail.python.org/mailman/listinfo/python-list
Re: Question RE urllib
On 12/17/2013 08:10 AM, Larry Martell wrote: On Tue, Dec 17, 2013 at 10:26 AM, Jeff James mailto:j...@jeffljames.com>> wrot So I'm using the following script to check our sites to make sure they are all up and some of them are reporting they are "down" when, in fact, they are actually up. These sites do not require a logon in order for the home page to come up. Could this be due to some port being blocked internally ? Only one of the sites reporting as down is "https" but all are internal sites. Is there some other component I should be including in the script ? There are about 30 or 40 sites that I have listed in all. I just use those in the following script as examples. Thanks import urllib sites = ["http://www.amazon.com/";, "https://internalsite.com/intranet.html";, etc.] for site in sites: try: urllib.urlopen(site) print site + " " except Exception, e: print site + " is down" -- https://mail.python.org/mailman/listinfo/python-list I've never used urllib, although I've done a fair amount of network programming at lower levels. Are you sure the report of "down" isn't simply a time out due to the server being busier than you expect when you hit it? -Bill After adding the line suggested by Larry, I was able to determine that the URLs reporting as "down" were actually sites requiring authentication in order to provide site content, so adding that line to the handler was at least enlightening in that respect. Thanks Larry. Glad to help. Here is some info on authenticating with urllib: http://docs.python.org/2.7/howto/urllib2.html#id6 It must be a network problem, cuz your code works fine: :w !python http://www.amazon.com/ http://google.com http://tobiah.org http://notavalidurl.com http://superreallyforsurenotavalidurlnokidding.com is down Tobiah -- https://mail.python.org/mailman/listinfo/python-list
Python and MIDI
Is there a module out there that would let me send a predetermined list of midi messages to a MIDI device in such a way that the timing would be precise enough for music? Thanks, Tobiah -- https://mail.python.org/mailman/listinfo/python-list
Re: dictionary with tuples
On 01/14/2014 01:21 PM, YBM wrote: Le 14/01/2014 22:10, Igor Korot a écrit : Hi, ALL, C:\Documents and Settings\Igor.FORDANWORK\Desktop\winpdb>python Python 2.7.5 (default, May 15 2013, 22:43:36) [MSC v.1500 32 bit (Intel)] on win32 Type "help", "copyright", "credits" or "license" for more information. dict = {} dict[(1,2)] = ('a','b') dict[(3,4)] = ('c','d') for (key1,key2),(value1,value2) in dict: ... print key1, " ", key2 ... print value1, " ", value2 ... Traceback (most recent call last): File "", line 1, in TypeError: 'int' object is not iterable What am I doing wrong? for ... in dict: is a way to iterate through dictionnary items, what you want to do can be done so: for (key1,key2),(value1,value2) in dict.items(): But it's (key1, value1), (key2, value2) -- https://mail.python.org/mailman/listinfo/python-list
Re: I am out of trial and error again Lists
On 10/22/2014 01:30 PM, Seymore4Head wrote: def nametonumber(name): lst=[""] for x,y in enumerate (name): lst=lst.append(y) print (lst) return (lst) a=["1-800-getcharter"] print (nametonumber(a))#18004382427837 The syntax for when to use a () and when to use [] still throws me a curve. For now, I am trying to end up with a list that has each character in "a" as a single item. a = "1-800-getcharter" list(a) ['1', '-', '8', '0', '0', '-', 'g', 'e', 't', 'c', 'h', 'a', 'r', 't', 'e', 'r'] -- https://mail.python.org/mailman/listinfo/python-list
Re: (test) ? a:b
On 10/22/2014 01:29 AM, ast wrote: Hello Is there in Python something like: j = (j >= 10) ? 3 : j+1; as in C language ? thx Out of all of the replies, I don't think anyone actually offered the answer: a if condition else b -- https://mail.python.org/mailman/listinfo/python-list