python3 package import difference?
I have an old library from 20 some years ago for use with python2, that is structured like this: rcs ├── dbi │ ├── __init__.py │ ├── dbi.py │ └── regos.py └── __init__.py -- *empty* the __init__.py file under 'rcs' is empty. The one under rcs.dbi contains: from dbi import * from regos import * With python2, I'd go: import rcs.dbi then I'd have access to stuff in regos.py as: rcs.dbi.feature() (Where 'feature' is defined in regos.py) When I do the same import with python3, I get: Traceback (most recent call last): File "/home/toby/me", line 1, in import rcs.dbi File "/usr/regos-1.0/lib/python/rcs/dbi/__init__.py", line 1, in from dbi import * ModuleNotFoundError: No module named 'dbi' What's changed, and how do I fix it? Thanks! -- https://mail.python.org/mailman/listinfo/python-list
Re: python repl vi mode line editing not working.
I see the literal 'escape' character + 'k', when it should let me edit previous commands. I did have to compile my own python because I'm using 2.7 on this machine. I figured it out. I needed to apt install libreadline-dev. -- https://mail.python.org/mailman/listinfo/python-list
Re: python repl vi mode line editing not working.
For this to work, the Python implementation should use the same readline library as your shell, I guess. It works in python3, so I guess my problem is that I'm compiling python (I think kubuntu dropped python2), but I don't see any relevant options in the configure help. -- https://mail.python.org/mailman/listinfo/python-list
Problem using mysql library
sinewave:toby ~(1)> python Python 2.7.18 (default, Jul 8 2024, 12:49:12) [GCC 13.2.0] on linux2 Type "help", "copyright", "credits" or "license" for more information. import MySQLdb Traceback (most recent call last): File "", line 1, in File "/usr/local/lib/python2.7/site-packages/MySQLdb/__init__.py", line 23, in (version_info, _mysql.version_info)) ImportError: this is MySQLdb version (1, 2, 5, 'final', 1), but _mysql is version (1, 4, 6, 'final', 0) I Googled this a lot, and saw many people with the same problem, but couldn't find an answer that helped. Thanks! Toby -- https://mail.python.org/mailman/listinfo/python-list
python repl vi mode line editing not working.
Kubuntu 24.04. sinewave:toby ~(1)> cat .inputrc set editing-mode vi set keymap vi sinewave:toby ~(1)> cat .editrc bind -v bind \\t rl_complete sinewave:toby ~(1)> python Python 2.7.18 (default, Jul 8 2024, 12:49:12) [GCC 13.2.0] on linux2 Type "help", "copyright", "credits" or "license" for more information. 1 1 2 2 ^[k I see the literal 'escape' character + 'k', when it should let me edit previous commands. I did have to compile my own python because I'm using 2.7 on this machine. Thanks for any help. Toby -- https://mail.python.org/mailman/listinfo/python-list
Re: Configuring an object via a dictionary
I should mention that I wanted to answer your question, but I wouldn't actually do this. I'd rather opt for your self.config = config solution. The config options should have their own namespace. I don't mind at all referencing foo.config['option'], or you could make foo.config an object by itself so you can do foo.config.option. You'd fill it's attributes in the same way I suggested for your main object. -- https://mail.python.org/mailman/listinfo/python-list
Re: Configuring an object via a dictionary
On 3/15/24 02:30, Loris Bennett wrote: Hi, I am initialising an object via the following: def __init__(self, config): self.connection = None self.source_name = config['source_name'] self.server_host = config['server_host'] However, with a view to asking forgiveness rather than permission, is there some simple way just to assign the dictionary elements which do in fact exist to self-variables? class Foo(): def __init__(self, config): for key, val in config.iteritems(): setattr(self, key, val) f = Foo({'cat': 'dog'}) print(f.cat) (outputs 'dog') -- https://mail.python.org/mailman/listinfo/python-list
Using pydal for standalone scripts
I am looking into creating a database abstraction library using pydal and mysql as the engine. I noticed that I have to specify a 'folder' with the connection string to tell pydal where to save "table files". So I'll have hundreds of different databases and install this library on many machines. Do I need to standardize a place for these files and make sure that directory exists on every machine that uses the library? It seems rather cumbersome. I mean, couldn't pydal have just put this information into the database in its own private table? Thanks! -- 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
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: 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: 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: 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
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
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
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: 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
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: 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
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: 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: 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
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
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: 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: 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: 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
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: 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
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
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: [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
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
[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: 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
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
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: 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
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: 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
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: 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
@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
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
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
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
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
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
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: 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
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: 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
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: ***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: 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: 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
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
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: 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
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
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
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
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
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
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
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
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
Re: API Help
> I still think it _could_ be the output of a Python repr() or similar > (something that is expected to be evaluated as a Python expression). It may be valid fodder for python eval(), but if it came from repr() It would have used single quotes, yes? -- https://mail.python.org/mailman/listinfo/python-list
Find out which module a class came from
I was viewing the python source for a program at work and came across a class name that I knew my company had written: import mycmp1 import mycmp2 import mycmp3 import mycmp4 import mycmp5 foo = FooClass() So I knew that FooClass was defined in one of those imports, but I thought it would be tedious to track down the location of all of those modules (is module.__file___ the best way) and scan them for the class definition. Is there a better way to find the definition of FooClass()? Thanks! -- https://mail.python.org/mailman/listinfo/python-list
Re: Who are the "spacists"?
> I wonder whether the tabs versus spaces divide is closely aligned to the > Windows versus Unix/Linux divide? > > It seems to me that Unix users are typically going to be using Unix tools > which often assume spaces are used for indentation, and consequently cope > badly with tabs. I can't think of any classic Unix tool that behaves in a way that would support this point of view. -- https://mail.python.org/mailman/listinfo/python-list
Re: The ternaery operator
On 03/16/2017 01:12 AM, Gregory Ewing wrote: > Stefan Ram wrote: > >> a if c else b >> >> Guido has invented something totally new. Why? > > It's arguably closer to the way you would say such a > thing in English. > > Consider the following sentences: > > "I wear my red shirt if it's Tuesday, else my green one." > > "I wear if it's Tuesday my red shirt, else my green one." > > Which one sounds more natural? > Actually, I see where now you are coming from: I wear (if a then b else c) as opposed to I wear (b if a else c) -- https://mail.python.org/mailman/listinfo/python-list
Re: The ternaery operator
On 03/16/2017 01:12 AM, Gregory Ewing wrote: > Stefan Ram wrote: > >> a if c else b >> >> Guido has invented something totally new. Why? > > It's arguably closer to the way you would say such a > thing in English. > > Consider the following sentences: > > "I wear my red shirt if it's Tuesday, else my green one." > > "I wear if it's Tuesday my red shirt, else my green one." > > Which one sounds more natural? > To be fair, the proper comparison would be: If it's Tuesday, I wear my red shirt, else my green one. I think it would be nice to have a way of getting the 'true' value as the return with an optional value if false. The desire comes about when the thing I'm comparing is an element of a collection: drugs['choice'] if drugs['choice'] else 'pot' Then I'm tempted to do: chosen = drugs['choice'] chosen if chosen else 'pot' I sometimes feel like doing: drugs['choice'] else 'pot' Tobiah -- https://mail.python.org/mailman/listinfo/python-list
Re: Extract items from string in db
On 03/14/2017 03:26 PM, DFS wrote: > I have a SQLite database with TEXT columns containing strings of the format: > > ['Item1: Value1 has,comma','Item2: has'apostrophe','Item3: Value3'] > > The brackets are part of the string. > > How can I unpack and access each item? > Item1: Value1 has,comma > Item2: has'apostrophe > Item3: Value3 > This problem is probably unsolvable for all cases because the data is apparently allowed to freely contain the characters that provide the string with its structure. Still, there are clues that enable the parsing of most normal cases you are likely to encounter. This hinges on the fact that "','" is unlikely to occur in the actual data: s = "['Item1: Value1 has,comma','Item2: has'apostrophe','Item3: Value3']" items = s[2:-2].split("','") # Toss brackets, first and last quotes for thing in items: key, val = thing.split(": ") print "%s: %s" % (key, val) Output: --- Item1: Value1 has,comma Item2: has'apostrophe Item3: Value3 -- 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
Re: windows and file names > 256 bytes
On 06/24/2015 10:45 AM, Albert-Jan Roskam wrote: Hi, Consider the following calls, where very_long_path is more than 256 bytes: [1] os.mkdir(very_long_path) [2] os.getsize(very_long_path) [3] shutil.rmtree(very_long_path) I am using Python 2.7 and [1] and [2] fail under Windows XP [3] fails the prefix) My questions: 1. How can I get the file size of very long paths under XP? As a workaround, could you use multiple calls to os.chdir() to get to where you need to do your operations, then use relative paths from there? Tobiah -- https://mail.python.org/mailman/listinfo/python-list
Re: Bitten by my C/Java experience
On 05/04/2015 08:20 AM, Cecil Westerhof wrote: Potential dangerous bug introduced by programming in Python as if it was C/Java. :-( I used: ++tries that has to be: tries += 1 Are there other things I have to be careful on? That does not work as in C/Java, but is correct syntax. One surprise for the new user is an otherwise handy rule of scope. A variable in a function will by default access any global variables of the same name *unless* it is assigned to in the function. def glob(): print "global:", foo def loc(): foo = 2 print "local:", foo def alt(): global foo foo = 1 print "altered:", foo foo = 3 glob() print "Original:", foo loc() print "Original:", foo alt() print "Original:", foo # Output ## global: 3 Original: 3 local: 2 Original: 3 altered: 1 Original: 1 -- https://mail.python.org/mailman/listinfo/python-list
subprocess and stdin.write(), stdout.read()
The docs for the subprocess.Popen() say: Use communicate() rather than .stdin.write, .stdout.read or .stderr.read to avoid deadlocks due to any of the other OS pipe buffers filling up and blocking the child process But if I want to send a string to stdin, how can I do that without stdin.write()? This seems to work: import subprocess as s thing = """ hey there foo man is here hey foo man is there so foo """ p = s.Popen(['grep', 'foo'], stdin = s.PIPE, stdout = s.PIPE) p.stdin.write(thing) print p.communicate() ## ('\they foo\n \tfoo there\n', None) Will this always avoid the deadlock problem? This also works: p = s.Popen(['grep', 'foo'], stdin = s.PIPE, stdout = s.PIPE) p.stdin.write(thing) p.stdin.close() print p.stdout.read() Is that vulnerable to deadlock? Is there a better way to write to and read from the same process? Thanks! Tobiah -- https://mail.python.org/mailman/listinfo/python-list
Syncing audio and video for casual recording
I decided I'd like to publish some youtube videos of me playing an instrument. The audio being the important bit, I'd like to use my existing mics, which I've been sending through a USB audio interface to my computer. I don't have any camera yet, other than a prosumer digital camera that does take decent video. The problem that I'm anticipating is the syncing of audio and video. Now, I do have a Tascam recorder with timecode, so maybe that's one way to approach this. I'm just guessing that any camera that has this would be expensive, but I didn't find out much in a very quick search. Aside from that, could I feed a decent audio signal into the camera and get the audio in that way? I've never done any video, so I'm quite in the dark about the camera part. Thanks, Tobiah --- This email is free from viruses and malware because avast! Antivirus protection is active. http://www.avast.com -- https://mail.python.org/mailman/listinfo/python-list
Re: [OFF-TOPIC] It is true that is impossible write in binary code, the lowest level of programming that you can write is in hex code?
On 11/04/2014 08:45 AM, françai s wrote: I intend to write in lowest level of computer programming as a hobby. It is true that is impossible write in binary code, the lowest level of programming that you can write is in hex code? What is the lowest level of programming computers that you can write ? Is binary code? Is hex code? My first computers at home were Z80 powered Timex's. I tried writing video games in BASIC, but the machines were to slow to animate anything at reasonable speeds. I knew about machine language from a high-school computer course (using and Apple IIe). I bought a book on the Z80, and started reading. My Z80 manual showed each 8-bit instruction's anatomy in Hex and binary. Some of the instructions used several bits to denote some aspect of the instruction. I got some graph paper, and started coding that way, using one square per bit, and one line per byte. I translated all the binary by brain into integer, and used BASIC programs to 'poke' the bytes into memory then execute at the starting address. This was all quite educational and extremely tedious. Eventually, when I found out that assemblers existed, I wrote a crude one in BASIC, and found that to be a luxury. Later when I got an Atari 800, and the assembler cartridge I actually wrote a working two player Tron type game in assembly. Having delved into all of this, I'd like to echo the sentiments of a previous poster, that assembly is really the place to start for a low level language. You get all of the control of machine language, with far less of the headaches. Depending on what you want out of your hobby, if a working program that is of some use is one of those things, then start with assembly. If you just want to geek out and write a program that can guess a number between 1 and 100 by using graph paper, then sure, go for binary writing. -- https://mail.python.org/mailman/listinfo/python-list
Re: (test) ? a:b
On 10/24/2014 10:27 AM, Chris Angelico wrote: On Sat, Oct 25, 2014 at 4:23 AM, Tobiah wrote: Out of all of the replies, I don't think anyone actually offered the answer: a if condition else b Jean-Michel did, the very first response. ChrisA I had to search for it. For some reason Thunderbird didn't thread that message with all the others. -- 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
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: Python Basics
for i in range(1,10): print (str(i)*i) Seymour, please don't do this. When you "help" someone by just giving him the answer to a homework problem, you get him past his immediate issue of "I need to submit my homework for this problem". That lets him get through his course without understanding the code he's creating (because he's not the one creating it). He'll either run into more trouble before graduating the course, or (far worse) he'll graduate successfully, without having the competence that the course is supposed to teach - and the world will be given a qualified programmer who doesn't know his stuff. That damages the world, damages the reputation of the course, and gives python-list a reputation as a homework assignment solver... none of which I want. I'm pretty sure you don't want it either. So don't do people's homework for them. PLEASE!! Wow. How do you react when someone does something that's actually harmful? I don't think you'd have the words! :) -- https://mail.python.org/mailman/listinfo/python-list
Re: Python Basics
Hi Chris I can't get the code to display the output as it should. I can get it to display like this: 1223335 or I can get it to display like this: 1 2 2 3 3 3 4 4 4 4 5 5 5 5 5 but not as has been asked in the question. Cheers Diarmuid Hint: 'a' * 4 '' -- https://mail.python.org/mailman/listinfo/python-list
Re: how to write a html to automatically display the dictionary?
On 09/23/2014 07:18 AM, luofeiyu wrote: x={'f1':1,'f2':2,'f3':3} how can i create the following html file automatically with python to display x ? f1 f2 f3 1 2 3 def tablefy(values): print "" for value in values: print "%s" % value print "" x = {'f1': 1,'f2': 2,'f3': 3} print "" tablefy(x.keys()) tablefy(x.values()) print "" -- https://mail.python.org/mailman/listinfo/python-list
Re: PEP8 and 4 spaces
Anyway, I gave up the 80 char line length long ago, having little feeling for some dolt Same to you. Haha, the language was too strong. The code I'm talking about is only going to be seen by a small group of programmers. The current trio has all been here for over 20 years. I'd be more concerned if the code were ever to be made public. on a Weiss terminal that for some reason needs to edit my code. I feel rather the same about the spaces and tabs, given that most people seem to be using editors these days that are configurable to show tabs a four characters. Any evidence out there that this part of PEP8 is becoming more optional or even obsolete, as I've heard others say about the 80 char line length? Just need ammo for when the hammer of code unification comes down. Just do the right thing and configure your editor to indent with spaces. -- https://mail.python.org/mailman/listinfo/python-list
Re: PEP8 and 4 spaces
On 07/03/2014 12:40 PM, Tim Chase wrote: On 2014-07-03 19:02, Grant Edwards wrote: That may be true, but that same person is going to have a difficult time editing the code. That's true with Notepad, but with dozens of other programming editors, code indented with spaces will read and edit prefectly. Not so for tab-indented code. A broken editor isn't the world's best argument. If I used an editor that changed my line-endings, randomly altered arbitrary characters, or tried to compress multiple spaces into one, I'd complain that the editor was broken. If a file has tab characters and my editor doesn't let me properly deal with characters, then THE EDITOR IS BROKEN. That said, even though I'm "-0" on "use 4 spaces rather than tabs", I conform to the standard to reduce interop headache even if I'd rather use tabs. -tkc I think your suggestion of having GIT handle the transformations is the way we'll go. nothing to quibble or worry about. Well put spaces in the repository since it still seems to be the community's preference and I'll convert to tabs with GIT on the fly. Problem solved. Thanks, Tobiah -- https://mail.python.org/mailman/listinfo/python-list
PEP8 and 4 spaces
Coworker takes PEP8 as gospel and uses 4 spaces to indent. I prefer tabs. Boss want's us to unify. The sole thing you get with spaces as far as I can tell, is that someone loading the code into Notepad will still see a 4 character indent. That may be true, but that same person is going to have a difficult time editing the code. Anyway, I gave up the 80 char line length long ago, having little feeling for some dolt on a Weiss terminal that for some reason needs to edit my code. I feel rather the same about the spaces and tabs, given that most people seem to be using editors these days that are configurable to show tabs a four characters. Any evidence out there that this part of PEP8 is becoming more optional or even obsolete, as I've heard others say about the 80 char line length? Just need ammo for when the hammer of code unification comes down. Thanks, Tobiah -- https://mail.python.org/mailman/listinfo/python-list
Re: python obfuscate
On 4/10/2014 6:29 PM, Wesley wrote: > Hi all, Does python has any good obfuscate? > > Currently our company wanna release one product developed by python > to our customer. But dont's wanna others see the py code. > > I googled for a while but mostly just say using pyc. Any better one? Does that work? If so, wouldn't that be a great solution? Toby -- https://mail.python.org/mailman/listinfo/python-list
Re: Geezer learns python
On 03/04/2014 03:03 PM, notbob wrote: I'm trying to learn python. I'm doing it via Zed Shaw's Learn Python the Hard Way. Sure enough, 16 lessons in and I've run aground. Is it OK for a painfully stupid ol' fart to ask painfully stupid noob questions, here? I'm a long time usenet fan and prefer it to irc. I've run Slackware for many yrs and know jes enough bash to get the drift of a slack script, but am no programmer, not by any stretch of the imagination. I really wanna succeed on this one and have signed up for an online python class from Rice U. I'd like to finish Zed's tutorial by the 24th of this month. I'm retired, so have the time to burn. Thnx. ;) nb All are welcome here. Try to narrow down the focus of the question, and where applicable, post source code and program output. -- https://mail.python.org/mailman/listinfo/python-list
Re: How does python know?
On 02/12/2014 12:17 PM, Tobiah wrote: I do this: a = 'lasdfjlasdjflaksdjfl;akjsdf;kljasdl;kfjasl' b = 'lasdfjlasdjflaksdjfl;akjsdf;kljasdl;kfjasl' print print id(a) print id(b) And get this: True 140329184721376 140329184721376 This works for longer strings. Does python compare a new string to every other string I've made in order to determine whether it needs to create a new object? Thanks, Tobiah Weird as well, is that in the interpreter, the introduction of punctuation appears to defeat the reuse of the object: >>> b = 'lasdfjlasdjflaksdjflakjsdfkljasdlkfjasl' >>> a = 'lasdfjlasdjflaksdjflakjsdfkljasdlkfjasl' >>> a is b True >>> a = 'la;sdfjlasdjflaksdjflakjsdfkljasdlkfjasl' >>> b = 'la;sdfjlasdjflaksdjflakjsdfkljasdlkfjasl' >>> a is b False >>> b = 'la.sdfjlasdjflaksdjflakjsdfkljasdlkfjasl' >>> a = 'la.sdfjlasdjflaksdjflakjsdfkljasdlkfjasl' >>> a is b False >>> a = 'lasdfjlasdjflaksdjflakjsdfkljasdlkfjasl' >>> b = 'lasdfjlasdjflaksdjflakjsdfkljasdlkfjasl' >>> a is b True Tobiah -- https://mail.python.org/mailman/listinfo/python-list
How does python know?
I do this: a = 'lasdfjlasdjflaksdjfl;akjsdf;kljasdl;kfjasl' b = 'lasdfjlasdjflaksdjfl;akjsdf;kljasdl;kfjasl' print print id(a) print id(b) And get this: True 140329184721376 140329184721376 This works for longer strings. Does python compare a new string to every other string I've made in order to determine whether it needs to create a new object? 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
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: 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
Re: Help me with this code PLEASE
All this problem arises because MySQL's hasn't got a datatype able to store an array of elements, a list. Um, yes it does. It's called a table. -- https://mail.python.org/mailman/listinfo/python-list
Re: urllib2 timeout issue
If run on my Debian Wheezy computer, or on my Debian Squeeze server, the answer is instantaneous : [...] urllib2.URLError: When run on my Raspberry Pi with Raspian Wheezy, the answer is identical but it takes 10 seconds. What happens when you use ping to resolve that address. Do you get the same results? If so, I'd say you have a DNS problem. Maybe you have two DNS servers listed in /etc/resolv.conf or similar, and the first one is unavailable, so it takes 10 seconds to fail over to the second working server. Tobiah -- https://mail.python.org/mailman/listinfo/python-list
Re: basic maze problem with turtle
On 10/13/2013 04:44 PM, Gary Herron wrote: On 10/13/2013 03:03 PM, Denis McMahon wrote: Except perhaps Nikos. Nikos can probably write you extremely elegant one line python solutions to any coding problem you describe to him. His solutions might suffer the very minor flaw of not working, but they're guaranteed to be Nikos certified aesthetically pure, and hence far superior to any solution more mundane coders might produce. That was uncalled for. There is already too much Nikos-bashing and Nikos-basher-bashing (and so on) in this newsgroup without dredging up even more in this completely unrelated request. Wait, doesn't this make you a Nikos-basher-basher? :() Gary Herron -- https://mail.python.org/mailman/listinfo/python-list
Re: Code golf challenge: XKCD 936 passwords
On 10/07/2013 11:17 PM, Chris Angelico wrote: Who's up for some fun? Implement an XKCD-936-compliant password generator in Python 3, in less code than this: print(*__import__("random").sample(open("/usr/share/dict/words").read().split("\n"),4)) Second challenge: Use it for generating all your passwords :) [1] https://en.wikipedia.org/wiki/Code_golf [2] http://xkcd.com/936/ ChrisA So how about finding the last word that starts with each lower case letter of the alphabet in turn: azures bywords czars ... Tobiah -- https://mail.python.org/mailman/listinfo/python-list
Re: Code golf challenge: XKCD 936 passwords
On 10/08/2013 09:07 AM, Tim Chase wrote: On 2013-10-08 15:36, Denis McMahon wrote: On Tue, 08 Oct 2013 08:33:48 -0400, Roy Smith wrote: In the old days, it used to be /usr/dict/words. Port Python to v6, and save another 6 characters :-) Doesn't matter where it is, a link to it exists at "/w" now ;) You prodigal...wasting a "/". I just symlinked it from my current working directory so it exists at "w". ;-) -tkc Yeah, but that's a lot of pixels! Link it to "'" in the current directory. -- https://mail.python.org/mailman/listinfo/python-list