Re: Which SQL module to use?
mrstephengross schrieb: > I'd like to do some basic SQL stuff in Python. It seems like there are > a heck of a lot of SQL modules for Python. What's the simplest and > easiest one to use? > > Thanks, > --Steve ([EMAIL PROTECTED]) > Do you have any DBMS in mind? Philipp -- http://mail.python.org/mailman/listinfo/python-list
str as param for timedelta
Hello Pythonistas I'm new to Python, I hope you understand my question. I would like to pass a parameter "gap" to a function. gap should be used there to create a timedelta Object. from datetime import * def f(gap): print (datetime.now() + datetime.timedelta(gap)) f('hours = -8') I read in the manual that datetime does accept ints, longs, or floats, which may be positive or negative. Same as the error message: "unsupported type for timedelta days component: str" I found out, that I can pass an Object def f1(deltaObj): print (datetime.now() + deltaObj) f1(timedelta(hours = -8)) I would prefer the first version, as it is easier to use the string for representation and so on. Is there any way to pass a string to the function and use it there for the timedelta? or you might say I missed some basic concepts... ... in any case, thank you very much! Phil -- http://mail.python.org/mailman/listinfo/python-list
Re: Initial nose experience
On 07/15/2012 08:58 PM, Roy Smith wrote: >> What motivated you to migrate from unittest to nose? > Mostly I was just looking for a better way to run our existing tests. > We've got a bunch of tests written in standard unittest, but no good way > to start at the top of the tree and run them all with a single command. Currently, $ python -m unittest does nothing useful (afaik). Would it break anything to look in . , ./test, ./tests for any files matching test_* , and execute those? - Philipp signature.asc Description: OpenPGP digital signature -- http://mail.python.org/mailman/listinfo/python-list
unittest: Improve discoverability of discover (Was: Initial nose experience)
On 07/16/2012 01:47 PM, Peter Otten wrote: > http://docs.python.org/library/unittest#test-discovery That's precisely it. Can we improve the discoverability of the discover option, for example by making it the default action, or including a message "use discover to find test files automatically" if there are no arguments? - Philipp signature.asc Description: OpenPGP digital signature -- http://mail.python.org/mailman/listinfo/python-list
Re: unittest: Improve discoverability of discover (Was: Initial nose experience)
On 07/16/2012 02:37 PM, Philipp Hagemeister wrote: > Can we improve the discoverability of the discover > option, for example by making it the default action, or including a > message "use discover to find test files automatically" if there are no > arguments? Oops, already implemented as of Python 3.2. Sorry, should've checked before. - Philipp signature.asc Description: OpenPGP digital signature -- http://mail.python.org/mailman/listinfo/python-list
Re: dict: keys() and values() order guaranteed to be same?
On 07/23/2012 01:23 PM, Henrik Faber wrote: > With an arbitrary dictionaty d, are d.keys() and d.values() > guaraneed to be in the same order? Yes. From the documentation[1]: If items(), keys(), values(), iteritems(), iterkeys(), and itervalues() are called with no intervening modifications to the dictionary, the lists will directly correspond. In most cases, you should simply use items() though. Can you elaborate on the use case for needing both keys() and values(), where items() is not applicable? - Philipp [1] http://docs.python.org/library/stdtypes.html#dict.items signature.asc Description: OpenPGP digital signature -- http://mail.python.org/mailman/listinfo/python-list
Re: from future import pass_function
Unlike the print statement, pass has no overboarding complexity (like >>, printing tuples, etc.) - it just serves as a marker (and practicality beats purity). And you don't ever want to use pass as a value (say, for map() or the right side of an assignment). In fact, if pass were a function, users could construct strange code like x = pass() def pass(): raise Exception('Are you slacking off? Get back to work!') And don't forget that while the parentheses mainly confuse users, they're also making it harder to type, and feel like useless overhead (similar to the parentheses in if (x): ). In fact, I'd argue that if pass were a function, None would be the better placeholder: try: do_something() except: None # 2 hard-to-type (on a German keyboard) characters shorter # (and probably way faster: No function call overhead and no need # to actually find out what pass happens to be in this context) - Philipp On 07/25/2012 10:40 AM, Ulrich Eckhardt wrote: > Hi! > > I just had an idea, it occurred to me that the pass statement is pretty > similar to the print statement, and similarly to the print() function, > there could be a pass() function that does and returns nothing. > > Example: >def pass(): >return > >try: >do_something() >except: >pass() > > > One thing I don't like about this is the syntax > >class foo(object): >pass() > > > What do you think? > > Uli signature.asc Description: OpenPGP digital signature -- http://mail.python.org/mailman/listinfo/python-list
Re: catch UnicodeDecodeError
Hi Jaroslav, you can catch a UnicodeDecodeError just like any other exception. Can you provide a full example program that shows your problem? This works fine on my system: import sys open('tmp', 'wb').write(b'\xff\xff') try: buf = open('tmp', 'rb').read() buf.decode('utf-8') except UnicodeDecodeError as ude: sys.exit("Found a bad char in file " + "tmp") Note that you cannot possibly determine the line number if you don't know what encoding the file is in (and what EOL it uses). What you can do is count the number of bytes with the value 10 before ude.start, like this: lineGuess = buf[:ude.start].count(b'\n') + 1 - Philipp On 07/25/2012 01:05 PM, jaroslav.dob...@gmail.com wrote: > it doesn't work signature.asc Description: OpenPGP digital signature -- http://mail.python.org/mailman/listinfo/python-list
Re: catch UnicodeDecodeError
On 07/26/2012 01:15 PM, Stefan Behnel wrote: >> exits with a UnicodeDecodeError. > ... that tells you the exact code line where the error occurred. Which property of a UnicodeDecodeError does include that information? On cPython 2.7 and 3.2, I see only start and end, both of which refer to the number of bytes read so far. I used the followin test script: e = None try: b'a\xc3\xa4\nb\xff0'.decode('utf-8') except UnicodeDecodeError as ude: e = ude print(e.start) # 5 for this input, 3 for the input b'a\nb\xff0' print(dir(e)) But even if you would somehow determine a line number, this would only work if the actual encoding uses 0xa for newline. Most encodings (101 out of 108 applicable ones in cPython 3.2) do include 0x0a in their representation of '\n', but multi-byte encodings routinely include 0x0a bytes in their representation of non-newline characters. Therefore, the most you can do is calculate an upper bound for the line number. - Philipp signature.asc Description: OpenPGP digital signature -- http://mail.python.org/mailman/listinfo/python-list
Re: catch UnicodeDecodeError
On 07/26/2012 02:24 PM, Stefan Behnel wrote: > Read again: "*code* line". The OP was apparently failing to see that > the error did not originate in the source code lines that he had > wrapped with a try-except statement but somewhere else, thus leading to the misguided impression that the exception was not properly caught by the except clause. Oops, over a dozen posts and I still haven't grasped the OP's problem. Sorry! and thanks for noting that. - Philipp signature.asc Description: OpenPGP digital signature -- http://mail.python.org/mailman/listinfo/python-list
Re: Linux shell to python
On 07/30/2012 09:05 AM, Vikas Kumar Choudhary wrote: > `lspci | grep Q | grep "$isp_str1" | grep "$isp_str2" | cut -c1-7' The rough Python equivalent would be import subprocess [ l.partition(' ')[0] # or l[:7], if you want to copy it verbatim for l in subprocess.check_output(['lspci']).splitlines() if 'Q' in l and isp_str1 in l and isp_str2 in l ] You can also just paste the whole pipeline with the shell=True parameter. That's not recommended though, and it's hard to correctly quote strings. - Philipp signature.asc Description: OpenPGP digital signature -- http://mail.python.org/mailman/listinfo/python-list
Re: Linux shell to python
On 07/30/2012 01:31 PM, Jürgen A. Erhard wrote: > On Mon, Jul 30, 2012 at 12:35:38PM +0200, Philipp Hagemeister wrote: >> import subprocess >> [ l.partition(' ')[0] # or l[:7], if you want to copy it verbatim >> for l in subprocess.check_output(['lspci']).splitlines() >> if 'Q' in l and isp_str1 in l and isp_str2 in l >> ] > > Ouch. A list comprehension spanning more than one line is bad code > pretty much every time. I didn't want to introduce a separate function, but as requested, here's the function version: def pciIds(searchWords=['Q', isp_str1, isp_str2]): for l in subprocess.check_output(['lspci']).splitlines(): if all(sw in l for sw in searchWords): yield l.partition(' ')[0] You could also separate the processing, like this: lines = subprocess.check_output(['lspci']).splitlines() lines = [l for l in lines if 'Q' in l and isp_str1 in l and isp_str2 in l] # Or: lines = filter(lambda l: 'Q' in l and isp_str1 in l and isp_str2 in l, lines) [l.partition(' ')[0] for l in lines] # Or: map(lambda l: l.partition(' ')[0], lines) But personally, I have no problem with three-line list comprehensions. Can you elaborate why the list comprehension version is bad code? Or more to the point, how would *you* write it? - Philipp signature.asc Description: OpenPGP digital signature -- http://mail.python.org/mailman/listinfo/python-list
Re: consistent input() for Python 2 and 3
On 08/02/2012 11:49 AM, Ulrich Eckhardt wrote: > try: > # redirect input() to raw_input() like Python 3 > input = raw_input > except NameError: > # no raw input, probably running Python 3 already > pass > What do you think? Any better alternatives? That's the generic solution, see http://python3porting.com/differences.html#input-and-raw-input . In my experience, it seems that input's main function is to allow beginners to learn the language, or to be used in short scripts. For a serious application, either curses or moving the input to the invocation arguments is often a better choice. - Philipp signature.asc Description: OpenPGP digital signature -- http://mail.python.org/mailman/listinfo/python-list
Re: Error help
Let's go thorugh this program: On 08/02/2012 12:58 PM, danielashi...@googlemail.com wrote: > import cPickle, pickle you probably want to transparently fall back to pickle if cPickle is not available. > print 'WELLCOME TO THE LIBET CLOCK EXPERIMENT DATA ANALYSIST' > file=raw_input('\nPLEASE ENTER THE NAME OF THE FILE YOU WISH TO ANALYSE: ') This should be a command-line option. Look for optparse, or use sys.argv[1] > pickle_file=open(file, 'r') > data=cPickle.load(pickle_file) You're opening a file in text mode, and leaking the handle. > file_name=file-'pck' + 'txt' You cannot subtract strings. You probably want to use + . Also, move this assignment down to where it's needed > partifipant_info=data'Participant Info'] You later use participant_info. typo? > first_block_data=data['First block data'] > second_block_data=data['Second block data'] > first_block_estimates=first_block_data['Estimated times'] > first_block_times=first_block_data['Actual times'] > second_block_estimates=second_block_data['Estimated times'] > second_block_times=second_block_data['Actual times'] This is not a useful data structure. You want: blocks = [{ 'estimates': data[name]['Estimated times'], 'actuals': data[name]['Actual Times'], } for name in ["First block data", "Second block data"}] or better yet, a sane pickle format. > def firstBlockDifferences(): This method should be called blockDifferences, and take a block as an argument, and return differenes. See http://docs.python.org/tutorial/controlflow.html#defining-functions for an introduction. > print '\nCALCULATING AVERAGE DIFFERENCES FOR BLOCK 1' This belongs in the calling method. > count=0 > first_block_differences=[] > total=0 > while count > differences=float(first_block_estimates[count])-float(first_block_times[count]) > if differences >= 180: > differences-=360 > elif differences <=-180: > differences+=360 What if the value is larger than 540 or smaller than -540? > total+=differences > differences=[differences] This line looks strange. Please use another variable name for values of another type. > first_block_differences+=differences If that's all there is to this function, have a look at writing a generator. If you delete the previous line, you can also write jsut first_block_differences.append(differences) > count+=1 Not required if you use zip above. > average_diff_first_block=total/len(first_block_estimates) > text_file.write('\nAverage differences for block 1: ', > average_diff_first_block) These two lines don't look as if they belong in this method. Better write another one that wraps the calculation and outputs stuff. > > def secondBlockDifferences(): Instead of writing two methods to do the same thing, write one with arguments. > (...) > text_file=open(file_name, 'w') You're leaking the handle. Use with(open(file_name, 'w')) as text_file: . > text_file.write('\nParticipant info: ', participant_info) > firstBlockDifferences() > secondBlockDifferences() - Philipp signature.asc Description: OpenPGP digital signature -- http://mail.python.org/mailman/listinfo/python-list
Re: Blue Screen Python
On 10/09/2012 09:37 AM, mikcec82 wrote: > In my script I open and close an html (in a FOR cycle); could be this the > problem? Unless you're running your Python script as a kernel driver (and you can't do that accidentally), there is no way that your user-space program should cause a bluescreen. This is an error in Windows (or one of the drivers), not in Python or your program. What you can do is insert your Windows DVD, boot from it, and click Repair. > Or is it possible that Python 2.7 is not compatible with Win7? No, even if a user-space program could legitimately cause a bluescreen, Python 2.7 still works fine one thousands of Win7 machines. Cheers, Philipp signature.asc Description: OpenPGP digital signature -- http://mail.python.org/mailman/listinfo/python-list
Re: what’s the difference between socket.send() and socket.sendall() ?
socket.socket.send is a low-level method and basically just the C/syscall method send(3) / send(2). It can send less bytes than you requested. socket.socket.sendall is a high-level Python-only method that sends the entire buffer you pass or throws an exception. It does that by calling send until everything has been sent or an error occurs. If you're using TCP with blocking sockets and don't want to be bothered by internals (this is the case for most simple network applications), use sendall. Otherwise, use send and make sure to read and process its return value. - Philipp On 01/07/2013 11:35 AM, iMath wrote: > what’s the difference between socket.send() and socket.sendall() ? > > It is so hard for me to tell the difference between them from the python doc > > so what is the difference between them ? > > and each one is suitable for which case ? > signature.asc Description: OpenPGP digital signature -- http://mail.python.org/mailman/listinfo/python-list
Re: Any Advice Would Be Greatly Appreciated
If you're looking for skilled developers, the best way to find them is probably to search their current work. http://careers.stackoverflow.com/ and the more experimental http://githire.com/ are two excellent developer-friendly solutions for that. - Philipp On 03/01/2012 12:08 AM, Greg Harezlak wrote: > Hello Python Community, > > I work for a mobile gaming startup in San Francisco, and we're heavily > staffing around skilled Python Developers. I've already submitted a job > posting to the Python.org website, but I was curious if anyone else had > some suggestions on where I could go to find some really awesome people. > Thanks in advance for your help. signature.asc Description: OpenPGP digital signature -- http://mail.python.org/mailman/listinfo/python-list
Re: multiprocessing: excepthook not getting called
multiprocessing just mimicks the threading module here, see http://bugs.python.org/issue1230540 . Why do you need excepthook in the first place? You can perfectly simulate it by wrapping the root method (target in your example) in a try .. catch: import multiprocessing import sys def printErrors(func): def wrapped(*args, **kwargs): try: func() except: print ('except: ', sys.exc_info()) return wrapped @printErrors def target(): raise ValueError() if __name__ == '__main__': p = multiprocessing.Process(target=target) p.start() p.join() # try it here in main target() Cheers, Philipp On 06/12/2012 11:02 PM, Dave Cook wrote: > Why doesn't my excepthook get called in the child process? > > import sys > import multiprocessing as mp > > def target(): > name = mp.current_process().name > def exceptHook(*args): > print 'exceptHook:', name, args > sys.excepthook = exceptHook > raise ValueError > > if __name__=='__main__': > p = mp.Process(target=target) > p.start() > p.join() > # try it here in main > target() > > Thanks, > Dave Cook signature.asc Description: OpenPGP digital signature -- http://mail.python.org/mailman/listinfo/python-list
Re: multiprocessing: excepthook not getting called
On 06/13/2012 11:00 AM, Dave Cook wrote: > Originally, I was trying to send formatted > tracebacks back to the main process on a queue. You can still do that: import multiprocessing import sys def queueErrors(q): def decorator(func): def wrapped(*args, **kwargs): try: func() except: q.put((multiprocessing.current_process().name, repr(sys.exc_info( return wrapped return decorator q = multiprocessing.Queue() @queueErrors(q) def target(): raise ValueError() if __name__ == '__main__': p = multiprocessing.Process(target=target) p.start() p.join() # try it here in main while True: pname,exc = q.get() print('Caught error in process %r: %s' % (pname, exc)) It gets somewhat harder when you also want to catch termination of threads, but you can just queue a special message. - Philipp signature.asc Description: OpenPGP digital signature -- http://mail.python.org/mailman/listinfo/python-list
Re: Download all youtube favorites with youtube-dl script
-BEGIN PGP SIGNED MESSAGE- Hash: SHA512 Hi Bill, the best way to ask for features or file bugs on youtube-dl is asking us at http://github.com/rg3/youtube-dl/issues . Luckily, I this list from time to time ;) Simply use youtube-dl --username u...@gmail.com --password secret :ytfav Best, Philipp On 09/26/2013 05:13 PM, Bill wrote: > I have been using the script youtube-dl > http://rg3.github.io/youtube-dl/ > > And I was wondering if there is a way to download all of a user's > favorites or uploads. > > The script has a functionality to download all videos in a txt > file. So if there is a way using the youtube API or JSON (none of > which I am familiar with) to bring up a list of all these videos > then it'd be a simple case putting these urls into a file. > > The problem is youtube displays favorites or user uploads in pages > or infinite scroll. So it is difficult to access them by the > BeautifulSoup module. > > > What do you suggest? -BEGIN PGP SIGNATURE- Version: GnuPG v1.4.14 (GNU/Linux) iQIcBAEBCgAGBQJSRFQmAAoJENtLVMukgmoYaz0P/ifoPqcx4dpShXyigwGxzhsa ht8sjIP8n3bNJ+J7Jvx0uM6Sv/Hu/U1CC09G1pT9nquHDYYvmko+MoBkXbc8JmlC R0qPhX0I2xGH9G1EL+83J4zzte3K7p5ErLY1V1S9cWuBKot16eKtrxhIgWxTMfE1 l93az4Uz4YLzUPYEXSO7pNX9cvxyrEjsqSJE3Jftn5ZqbUO46M+7gMKG2g46C/W4 IQtg2v9cHE3xKV5c+wCFjjIHtOGg+leOTMFdiD6oIa/uNfV/3tzpiyQ1e2QgyrvU UK4zz3TxqxWswDTrxRdc7fFNAGoNSrxU2hwyvjc/CGehORv7ktBjJJbtt3PfvHsi nov+OEIToDFTO1nCzQ39qQP0Ibl0LpNbvJGWyJqubFsZd0uiU1EwONXFchNwHeil Yce4DT8Tzf4zv6y3YNJCz1RCM1G308vQav539w6D7vfIUc5F28gnWKkd5NIcCpyu URVWp0HxV7d+kCekbxhnd+Ah/XvsrHhkI3cxOHvc1QjGwToRWawJQT0LD72E6PqW MmnOUTZhrxebyAx1HEt45l19fuW/TfwCWWzAtRscr8uFLFf0/Hwm41tSo8FjxqK2 OVZAckmVYIKP0F+u6hcSg/INl6rs6R+Co4/S8aFdKh2N16wmwQ7hevoTIpXIFwwK hkpwAUdlQxIWzSe8uJMV =nRz7 -END PGP SIGNATURE- -- https://mail.python.org/mailman/listinfo/python-list
string encoding regex problem
Hello, I have defined a function with: def URLReader(url) : try : f = urllib2.urlopen(url) data = f.read() f.close() except Exception, e : raise MyError.StopError(e) return data which get the HTML source code from an URL. I use this to get a part of a HTML document without any HTML parsing, so I call (I would like to get the download link of the boost library): found = re.search( "href=\"/projects/boost/files/latest/download\?source=files\" title=\"/boost/(.*)", Utilities.URLReader("http://sourceforge.net/projects/boost/files/boost/";) ) if found == None : raise MyError.StopError("Boost Download URL not found") But found is always None, so I cannot get the correct match. I didn't find the error in my code. Thanks for help Phil-- https://mail.python.org/mailman/listinfo/python-list
Re: string encoding regex problem
On 2014-08-16 00:48:46 +, Roy Smith said: In article , Philipp Kraus wrote: found = re.search( "http://sourceforge.net/projects/boost/files/boost/";) ) if found == None : raise MyError.StopError("Boost Download URL not found") But found is always None, so I cannot get the correct match. I didn't find the error in my code. I would start by breaking this down into pieces. Something like: data = Utilities.URLReader("http://sourceforge.net/projects/boost/files/boost/";) ) print data found = re.search( " Now at least you get to look at what URLReader() returned. Did it return what you expected? If not, then there might be something wrong in your URLReader() function. I have check the result of the (sorry, I forgot this information on my first post). The URLReader returns the HTML code of the URL, so this seems to work correctly If it is what you expected, then I would start looking at the pattern to see if it's correct. Either way, you've managed to halve the size of the problem. The code works till last week correctly, I don't change the pattern. My question is, can it be a problem with string encoding? Did I mask the question mark and quotes correctly? Phil -- https://mail.python.org/mailman/listinfo/python-list
Re: string encoding regex problem
Hi, On 2014-08-16 09:01:57 +, Peter Otten said: Philipp Kraus wrote: The code works till last week correctly, I don't change the pattern. Websites' contents and structure change sometimes. My question is, can it be a problem with string encoding? Your regex is all-ascii. So an encoding problem is very unlikely. found = re.search( "href=\"/projects/boost/files/latest/download\?source=files\" title=\"/boost/(.*)", data) Did I mask the question mark and quotes correctly? Yes. A quick check... data = urllib.urlopen("http://sourceforge.net/projects/boost/files/boost/";).read() re.compile("/projects/boost/files/latest/download\?source=files.*?>").findall(data) ['/projects/boost/files/latest/download?source=files" title="/boost-docs/1.56.0/boost_1_56_pdf.7z: released on 2014-08-14 16:35:00 UTC">'] ...reveals that the matching link has "/boost-docs/" in its title, so the site contents probably did change. I have create a short script: - #!/usr/bin/env python import re, urllib2 def URLReader(url) : f = urllib2.urlopen(url) data = f.read() f.close() return data print re.match( "\.*\<\/small\>", URLReader("http://sourceforge.net/projects/boost/";) ) - Within the data the string "boost_1_56_0.tar.gz" should be machted, but I get always a None result on the re.match, re.search returns also a None. I have tested the regex under http://regex101.com/ with the HTML code and on the page the regex is matched. Can you help me please to fix the problem, I don't understand that the match returns None Thanks Phil-- https://mail.python.org/mailman/listinfo/python-list
Re: From Python on Solaris to Python on LINUX
> What are the traps to be avoided? Assuming you're not using any OS features (scan the code for "/dev" and "/proc"), the transition from Solaris to Linux will be seamless. Your main problem will be the transition from the archaic Python 2.3 to a modern one. Luckily, all 2.x Pythons should be backwards-compatible. In summary, your application should work just fine (although being written in 2.3, it's probably not as maintainable as a modern application would). > What is the most recent version on LINUX? There are multiple Linux distributions which can differ quite a lot. debian, Ubuntu, and CentOS are popular ones. As you can see on http://www.debian.org/CD/ , the current debian version is 6.0. As you can't see at the moment on http://kernel.org/ , the current Linux kernel version is 3.0 (although most distribution will want to test the kernel and therefore include a slightly older one). -- Philipp signature.asc Description: OpenPGP digital signature -- http://mail.python.org/mailman/listinfo/python-list
Re: Code Review
Instead of comments, you can often use docstrings (http://www.python.org/dev/peps/pep-0257/ ): This is hard to read due to the indentation, and cannot be accessed programmatically: #Update the GUI def update_gui(self, new_word): Instead, use this: def update_gui(self, new_word): "Update the GUI." Now, you can use help(Message) to get information about the method. You'll notice "Update the GUI." is not helpfull at all for a method called update_gui. Comments (and docstrings) that reproduce the method name are not useful. A couple of minor things: * If you delete code, delete it, don't comment it out. * Use newlines between two methods. Compare def a(self): pass def b(self): pass def c(self): pass with def a(self): pass def b(self): pass def c(self): pass The latter looks neat and not nearly as crammed as the former. * Don't use newlines where they shouldn't be, for example in if val == 0: label.unbind('') * Even if it's just the comments, typos make a very bad impression of a coder and the code. I'd automatically assume lots of bugs and untested code when I see more than the occasional typo. * GUI programming is fun, but does not lend itself to structured programming and good practices. You should never use global. Instead, have an object encapsulating the state and pass that object to the method itself or its object. * Don't commit .pyc files, they're totally useless. Since python 2.6, you can add the following in your .bashrc to make python not create them: export "PYTHONDONTWRITEBYTECODE=dont" In git, you can add the following in your project's .gitignore or ~/.gitignore_global: *.pyc [More on .gitignore: http://help.github.com/ignore-files/ ] * Otherwise, the code looks pretty good for a beginner. You may, however, want to replace def word_not_found(word): if word in searchedwordset: return 0 else: return 1 with just: def word_not_found(word): return word not in searchedwordset (or just skip this method and write word not in searchedwordset). Cheers, Philipp Emeka wrote: > Hello All, > > While learning Python I put together another Text Twist. I would want > somebody to go through it and comment. > https://github.com/janus/Text-Twist > > signature.asc Description: OpenPGP digital signature -- http://mail.python.org/mailman/listinfo/python-list
Re: python-based downloader (youtube-dl) missing critical feature ...
-BEGIN PGP SIGNED MESSAGE- Hash: SHA512 As already said, you should file your request at https://github.com/rg3/youtube-dl/issue , not here. A few things to note: * Not all sites necessarily send the Content-Length header. * RTMP URLs would have to be treated differently * Sending a Range header might allow for a better implementation. Why do you want to restrict the filesize of the download in the first place? I can't see a use case, but that doesn't mean there isn't one. Due to me not having lots of time at the moment, your best chance to get any youtube-dl feature implemented is providing a patch (in form of a github pull-request, if possible). - -- Philipp (youtube-dl developer) l...@mail.python.org wrote: > python-based youtube-dl > ~ > http://rg3.github.com/youtube-dl/ > ~ > is sorely missing a flag in order to indicate the maximum file length of the > data feed it would download (well, unless, for some reason, it is considered > a "feature"). > ~ > I wonder what developers were thinking about when they came up this nice > piece of code. If you actually look in the code > ~ > ... > data = urllib2.urlopen(basic_request) > content_length = data.info()['Content-Length'] > ... > ~ > you will see they get the content length of the actual data feed and they > also print the progress status based on the content length > ~ > Implementing an if statement a la: > ~ > max_indicated_content_length = self.params.get('max_content_length', None); > ~ > if( content_length > max_indicated_content_length ){ [do not download, just > report "data feed too large"] } > else{ [do] } > ~ > shouldn't be hard at all > ~ > youtube-dl is under the Creative Commons License copyrighted by 2006-2011 > Ricardo Garcia Gonzalez and maintained by him and a group of python developers > ~ > They are the ones keeping a mental map of that project. It would be a plus > if they implement this feature, but anyother python developer can implemented > (please, let me know if/when you do) > ~ > lbrtchx -BEGIN PGP SIGNATURE- Version: GnuPG v1.4.11 (GNU/Linux) iEYEAREKAAYFAk6z3mMACgkQ9eq1gvr7CFyr1wCgpqf8xuORDC4LBVY8WFmtAufG k+AAoIX+mXa7SGLULP2M67IQ34sBgk1o =duyH -END PGP SIGNATURE- -- http://mail.python.org/mailman/listinfo/python-list
Re: youtube-dl: way to deal with the size cap issue + new errors + issues ...
-BEGIN PGP SIGNED MESSAGE- Hash: SHA512 As a general rule, feel free to contact youtube-dl developers and users at https://github.com/rg3/youtube-dl/issues/ . youtube-dl is just one application, which happens to be written in Python. l...@mail.python.org wrote: > I did find my way (through a silly hack) to get all files within a size > range without waiting for youtube-dl to be "enhanced". You may be able to send a HEAD request to the URL, but there's no guarantee the response will contain a Content-Length header. In fact, there will never be a Content-Lenght header for infinite HTTP streams. Also, RTMP URLs are way more complicated. > I have also been getting errors reporting: > RTMP download detected but "rtmpdump" could not be run You need rtmpdump. See http://rtmpdump.mplayerhq.hu/ for instructions on how to install it. > It would be very helpful if you could redirect youtube-dl errors to a > separate file you would indicate via a flag If you think so, please open an issue. Do not forget to consider the usefulness not only for your specific application, but also of other applications. I think the command-line API (https://github.com/rg3/youtube-dl/issues/152) will be your best shot. Note that you can already redirect youtube-dl's output to a file, just like any other shell program: $ youtube-dl uHlDtZ6Oc3s > log will write a file log that contains all of youtube-dl's output. If the return code is not 0, an error has occured. Cheers, Philipp youtube-dl developer -BEGIN PGP SIGNATURE- Version: GnuPG v1.4.11 (GNU/Linux) iEYEAREKAAYFAk7KvygACgkQ9eq1gvr7CFw6GwCfeaF0TPNonTCaXVBDnmDBPio2 qVQAn2/JQzTbBYs+pe50t4qVCjxY+BLy =o6uC -END PGP SIGNATURE- -- http://mail.python.org/mailman/listinfo/python-list
codecs in a chroot / without fs access
I want to forbid my application to access the filesystem. The easiest way seems to be chrooting and droping privileges. However, surprisingly, python loads the codecs from the filesystem on-demand, which makes my program crash: >>> import os >>> os.getuid() 0 >>> os.chroot('/tmp') >>> ''.decode('raw-unicode-escape') Traceback (most recent call last): File "", line 1, in (Interestingly, Python goes looking for the literal file "" in sys.path. Wonder what happens if I touch /usr/lib/python2.7/dist-packages/). Is there a neat way to solve this problem, i.e. have access to all codecs in a chroot? If not, I'd love to have a function codecs.preload_all() that does what my workaround does: import codecs,glob,os.path encs = [os.path.splitext(os.path.basename(f))[0] for f in glob.glob('/usr/lib/python*/encodings/*.py')] for e in encs: try: codecs.lookup(e) except LookupError: pass # __init__.py or something enumerate /usr/lib/python.*/encodings/*.py and call codecs.lookup for every os.path.splitext(os.path.basename(filename))[0] Dou you see any problem with this design? - Philipp signature.asc Description: OpenPGP digital signature -- http://mail.python.org/mailman/listinfo/python-list
Re: any chance for contracts and invariants in Python?
I don't know anything about the status of this PEP or why it hasn't been implemented, but here's what strikes me as obviously complex: Doesn't one need to traverse the entire class hierarchy on every function call? So if I have class A: def foo(self): return 1 class B(A): "inv: True" def foo(self): "post: __return__ == 2" return 2 Now, I have f = B().foo f() . What does Python do? If your answer is 1. Look up class of f 2. Check its invariant (succeeds) 3. Execute the function 4. Check post conditions of f (succeeds) 5. return 2 Then what will I get if I run any of the following programs: A.foo.__doc__ = 'inv: __return__ == 1' f() def _foo(self): 'post: __return__ == 3' A.foo = _foo f() A.__doc__ = 'inv: False' f() So any implementation has to choose one of the following: 1. Ignore invariants and postconditions of inherited classes - defeats the purpose. 2. Only respect definitions in classes and methods in the original definition, which would be unpythonic 3. Only respect the "original" definitions, for some value of original. Simarily, this would break monkey patching. 4. Update all subclasses whenever something changes. 5. Traverse the entire class hierarchy for every method call. Which option should be picked? Additionally, the reference implementation is not actually a fork of cpython (or a metaclass), but a Python script that - as far as I understand - I have to call manually to start using contracts. - Philipp On 14.02.2013 12:42, mrk...@gmail.com wrote: > > This PEP seems to be gathering dust: > > http://www.python.org/dev/peps/pep-0316/ > > I was thinking the other day, would contracts and invariants not be better > than unit tests? That is, they could do what unit tests do and more, bc they > run at execution time and not just at development time? > signature.asc Description: OpenPGP digital signature -- http://mail.python.org/mailman/listinfo/python-list
Re: pypi changelog api
Hi Gregg, to get a smaller response, you can simply pass in a timestamp, like this: >>> client = xmlrpclib.ServerProxy('http://pypi.python.org/pypi') >>> import time >>> client.changelog(int(time.time() - 600)) [['vs.bootstrap.plonetheme', '1.0.1', 1361451748, 'update description, classifiers'], ['numericalunits', '1.11', 1361451759, 'new release'], ['numericalunits', '1.11', 1361451760, 'add source file numericalunits-1.11.tar.gz'], ['autobahn_rce', '0.6.0', 1361451798, 'remove'], ['vs.bootstrap.plonetheme', '1.0.1', 1361451816, 'update description, classifiers'], ['vs.bootstrap.plonetheme', '1.0.1', 1361451882, 'update description, classifiers'], ['autobahn_rce', '0.5.9', 1361451956, 'new release'], ['autobahn_rce', '0.5.9', 1361451971, 'add source file autobahn_rce-0.5.9.tar.gz']] I don't think there's way to get older chunks of the changelog though. What would you need those for? If you need the entire changelog, just download it once (it's not that large, barely 40MB). Here it is, up until 1361452402 (now): http://phihag.de/2013/pypi-changelog-2013-02-20.json.bz2 What I'd like is a real-time push service of changelog entries, but I'm not certain that would be scalable. Cheers, Philipp On 02/18/2013 02:16 AM, Gregg Caines wrote: > Hey all, > > I'm trying to write a script that tracks changes on pypi, and I've come > across the xmlrpc interface, specifically the 'changelog' api. It's > definitely what I'm looking for, but I get an absolutely massive xml response > from it at once and I was hoping there might be either some way to "page" > through it with mulitple requests, or a different-but-similar API. > > Thanks in advance, > Gregg signature.asc Description: OpenPGP digital signature -- http://mail.python.org/mailman/listinfo/python-list
Re: pypi changelog api
Just FYI, PyPi already has an RSS feed: https://pypi.python.org/pypi?:action=rss And instead of mailing the author, you should probably open an issue (or better yet, a pull request) at https://github.com/crateio/crate.web/issues For that matter - how does crate.io update their PyPi mirror? Cheers, Philipp On 02/21/2013 02:52 PM, Michael Herman wrote: > I'd love to see https://crate.io/ set up an API or at the very least an RSS > feed for tracking changes. I've emailed the author about this. I think if > enough people do, an RSS feed would be easy to setup. > > > On Thu, Feb 21, 2013 at 5:33 AM, Philipp Hagemeister wrote: > >> Hi Gregg, >> >> to get a smaller response, you can simply pass in a timestamp, like this: >> >>>>> client = xmlrpclib.ServerProxy('http://pypi.python.org/pypi') >>>>> import time >>>>> client.changelog(int(time.time() - 600)) >> [['vs.bootstrap.plonetheme', '1.0.1', 1361451748, 'update description, >> classifiers'], ['numericalunits', '1.11', 1361451759, 'new release'], >> ['numericalunits', '1.11', 1361451760, 'add source file >> numericalunits-1.11.tar.gz'], ['autobahn_rce', '0.6.0', 1361451798, >> 'remove'], ['vs.bootstrap.plonetheme', '1.0.1', 1361451816, 'update >> description, classifiers'], ['vs.bootstrap.plonetheme', '1.0.1', >> 1361451882, 'update description, classifiers'], ['autobahn_rce', >> '0.5.9', 1361451956, 'new release'], ['autobahn_rce', '0.5.9', >> 1361451971, 'add source file autobahn_rce-0.5.9.tar.gz']] >> >> I don't think there's way to get older chunks of the changelog though. >> What would you need those for? >> >> If you need the entire changelog, just download it once (it's not that >> large, barely 40MB). Here it is, up until 1361452402 (now): >> >> http://phihag.de/2013/pypi-changelog-2013-02-20.json.bz2 >> >> What I'd like is a real-time push service of changelog entries, but I'm >> not certain that would be scalable. >> >> Cheers, >> >> Philipp >> >> >> On 02/18/2013 02:16 AM, Gregg Caines wrote: >>> Hey all, >>> >>> I'm trying to write a script that tracks changes on pypi, and I've come >> across the xmlrpc interface, specifically the 'changelog' api. It's >> definitely what I'm looking for, but I get an absolutely massive xml >> response from it at once and I was hoping there might be either some way to >> "page" through it with mulitple requests, or a different-but-similar API. >>> >>> Thanks in advance, >>> Gregg >> >> >> >> -- >> http://mail.python.org/mailman/listinfo/python-list >> >> > signature.asc Description: OpenPGP digital signature -- http://mail.python.org/mailman/listinfo/python-list
Re: pypi changelog api
On 02/21/2013 02:58 PM, Michael Herman wrote: > Oh - and I haven't tried this site, but you may be able to set something up > on there to email when the changelog is updated. > > http://www.changedetection.com/ They just query the whole page - I could do that myself, easily. But the problem is that that would mean lots of load on PyPi (if you query every minute or so) and outdated packages (if you query less often than that). Keeping a connection that PyPi would push to seems to be much cleaner. - Philipp signature.asc Description: OpenPGP digital signature -- http://mail.python.org/mailman/listinfo/python-list
Re: ** Please Rank These Learning Sources **
> http://learnpythonthehardway.org/book/ I have never used that myself, but I have seeen plenty of stackoverflow and student questions about it. In short, it's horrible. The book mostly consists of basic Python programs, and beginners often fail to grasp even the most basic structures demonstrated, mainly because they're not explained. The book has some of the easy-to-approach informality of, say, the Head First ones, but fails to contain the the actual explanations for it. (And I have no idea why one would start with Python 2.x, given that everything's strange in there - instead of relying on the intuitive grasp that both "a" and "ä" are single character strings, and that print is a function like any other, they have to work with a lot of magic and hand-waving) - Philipp signature.asc Description: OpenPGP digital signature -- http://mail.python.org/mailman/listinfo/python-list
Re: Issues a longer xpath expression
Hi anonymous, your code is working perfectly right. It's just that the only time that you find anything matching //div[@class="col f-cb"] is this one: 名称 视频下载 课程简介 And obviously, there's no in there, so the xpath won't match. Cheers, Philipp On 02/22/2013 02:24 AM, python wrote: > I am having issues with the urllib and lxml.html modules. > > Here is my original code: > > import urllib > import lxml.html > down='http://v.163.com/special/visualizingdata/' > file=urllib.urlopen(down).read() > root=lxml.html.document_fromstring(file) > xpath_str="//div[@class='down s-fc3 f-fl']/a" > urllist=root.xpath(xpath_str)for url in urllist:print url.get("href") > > When run, it returns this output: > > http://mov.bn.netease.com/movieMP4/2012/12/A/7/S8H1TH9A7.mp4 > http://mov.bn.netease.com/movieMP4/2012/12/D/9/S8H1ULCD9.mp4 > http://mov.bn.netease.com/movieMP4/2012/12/4/P/S8H1UUH4P.mp4 > http://mov.bn.netease.com/movieMP4/2012/12/B/V/S8H1V8RBV.mp4 > http://mov.bn.netease.com/movieMP4/2012/12/6/E/S8H1VIF6E.mp4 > http://mov.bn.netease.com/movieMP4/2012/12/B/G/S8H1VQ2BG.mp4 > > But, when I change the line > > xpath_str='//div[@class="down s-fc3 f-fl"]//a' > > into > > xpath_str='//div[@class="col f-cb"]//div[@class="down s-fc3 f-fl"]//a' > > that is to say, > > urllist=root.xpath('//div[@class="col f-cb"]//div[@class="down s-fc3 > f-fl"]//a') > > I do not receive any output. What is the flaw in this code? > it is so strange that the shorter one can work,the longer one can not,they > have the same xpath structure! > > > signature.asc Description: OpenPGP digital signature -- http://mail.python.org/mailman/listinfo/python-list
Re: Programmatically finding "significant" data points
erikcw <[EMAIL PROTECTED]> wrote: > I have a collection of ordered numerical data in a list. The numbers > when plotted on a line chart make a low-high-low-high-high-low (random) > pattern. I need an algorithm to extract the "significant" high and low > points from this data. I am not sure, what you mean by 'ordered' in this context. As pointed out by Jeremy, you need to find an appropriate statistical test. The appropriateness depend on how your data is (presumably) distributed and what exactly you are trying to test. E.g. do te data pints come from differetn groupos of some kind? Or are you just looking for extreme values (outliers maybe?)? So it's more of statistical question than a python one. cu Philipp -- Dr. Philipp Pagel Tel. +49-8161-71 2131 Dept. of Genome Oriented BioinformaticsFax. +49-8161-71 2186 Technical University of Munich http://mips.gsf.de/staff/pagel -- http://mail.python.org/mailman/listinfo/python-list
Re: where or filter on list
[EMAIL PROTECTED] <[EMAIL PROTECTED]> wrote: > Can anybody tell me how to to find the nearest value to zero in a > list? > >>> foo = [-5,-1,2,3] # nearest value to zero ? > >>> [value for value in foo if math.fabs(value) == min([int(math.fabs(x)) for > >>> x in foo])] > [-1] > Something simpler ? Maybe something like this: mindist = min(map(abs, foo)) filter(lambda x: abs(x) == mindist, a)[0] Only annoyance: we compute abs twice for each value. We could probably avoid that by using reduce() and a suitable function... > How to extend this function to any given value ? By subtracting the desired value from foo. cu Philipp -- Dr. Philipp Pagel Tel. +49-8161-71 2131 Dept. of Genome Oriented BioinformaticsFax. +49-8161-71 2186 Technical University of Munich http://mips.gsf.de/staff/pagel -- http://mail.python.org/mailman/listinfo/python-list
Re: Better way to replace/remove characters in a list of strings.
Chris Brat <[EMAIL PROTECTED]> wrote: > Is there a better way to replace/remove characters (specifically ' and > " characters in my case, but it could be anything) in strings in a > list, than this example to replace 'a' with 'b': x = map(lambda foo: foo.replace('a', 'b'), x) cu Philipp -- Dr. Philipp Pagel Tel. +49-8161-71 2131 Dept. of Genome Oriented BioinformaticsFax. +49-8161-71 2186 Technical University of Munich http://mips.gsf.de/staff/pagel -- http://mail.python.org/mailman/listinfo/python-list
Re: The Modernization of Emacs
Ever came to your mind that there are people (programmers and others) who will not use emacs for their day-to-day work simply because they have tools that suit them better for the work they have to do (Eclipse for me, as an example)? Except from that: I personally don't feel that your rantings are interesting enough to qualify for a 4 groups X-post ... this sort of article goes well into a blog, but not so much on programmers newsgroups (which are used for Q&A imho). -- http://mail.python.org/mailman/listinfo/python-list
os.popen and broken pipes
Hi Pythoneers, I need to process a large number of files which have been packed by the UNIX compress tool (*.Z files). As I am not aware of a compress equivalent of the gzip, zipfile or bzip2 modules, I thought I'd use the uncompress or zcat commands directly to deal with the files: for filename in file_list: file = os.popen('uncompress -c '+filename, 'r') do_something(file) file.close() This works fine for some files but results in 'write error onstdout: Broken pipe' emitted by uncompress for others. Using zcat instead of uncompress changes the wording of the error message but not the result. I tried to give popen a large bufsize argument but that didn't really help. Probably I'm overlooking something obvious here but right now I can't see it. Any hints? cu Philipp -- Dr. Philipp Pagel Tel. +49-8161-71 2131 Dept. of Genome Oriented BioinformaticsFax. +49-8161-71 2186 Technical University of Munich http://mips.gsf.de/staff/pagel -- http://mail.python.org/mailman/listinfo/python-list
Re: os.popen and broken pipes
Antoon Pardon <[EMAIL PROTECTED]> wrote: > On 2007-02-09, Philipp Pagel <[EMAIL PROTECTED]> wrote: > > for filename in file_list: > > file = os.popen('uncompress -c '+filename, 'r') > > do_something(file) > > file.close() > > > > This works fine for some files but results in > > > > 'write error onstdout: Broken pipe' > As far as I can tell, your do_something doesn't consume the entire file. > So you close the file prematurly, which results in the uncompress/zcat > program trying to write to a pipe that is closed on the otherside, > giving you the above message. You are right: some of the files do not fulfill certain critereia causing so_somehting() to return before the entire file is processed. Thanks! cu Philipp -- Dr. Philipp Pagel Tel. +49-8161-71 2131 Dept. of Genome Oriented BioinformaticsFax. +49-8161-71 2186 Technical University of Munich http://mips.gsf.de/staff/pagel -- http://mail.python.org/mailman/listinfo/python-list
Re: os.popen and broken pipes
Chris <[EMAIL PROTECTED]> wrote: > It could easily be the 2gig file size limitation, how large are the > extracts? The files are much smaller than that, so that's not the issue. Anyway, Antoon pointed me in the right direction. Thanks for the help Philipp -- Dr. Philipp Pagel Tel. +49-8161-71 2131 Dept. of Genome Oriented BioinformaticsFax. +49-8161-71 2186 Technical University of Munich http://mips.gsf.de/staff/pagel -- http://mail.python.org/mailman/listinfo/python-list
Re: Glob returning an empty list when passed a variable
Neil Webster <[EMAIL PROTECTED]> wrote: > area_name_string = '"*% s*"' % (Area_name) > os.chdir(Input) > filename = glob.glob(area_name_string) Too many quotation marks. >>> Area_name='Foo' >>> '"*% s*"' % (Area_name) '"*Foo*"' Unless there are files with funny names containing '"' you will not get a match. cu Philipp -- Dr. Philipp Pagel Tel. +49-8161-71 2131 Dept. of Genome Oriented BioinformaticsFax. +49-8161-71 2186 Technical University of Munich http://mips.gsf.de/staff/pagel -- http://mail.python.org/mailman/listinfo/python-list
Re: Finding a tuple in a tuple
[EMAIL PROTECTED] wrote: > t1 = ("ONE","THREE","SIX") > t2 = ("ONE","TWO","THREE") > t3 = ("TWO","FOUR","FIVE","SIX") > t4 = ("TWO",) > t5 = ("TWO","FIVE") > What I want to do is return true if any member of tuple t1 is found in > the remaining tuples. Another way to go instead of using sets, although probably less elegant: >>> True in [x in t1 for x in t2] True >>> True in [x in t1 for x in t3] True >>> True in [x in t1 for x in t4] False >>> True in [x in t1 for x in t5] False cu Philipp -- Dr. Philipp Pagel Tel. +49-8161-71 2131 Dept. of Genome Oriented BioinformaticsFax. +49-8161-71 2186 Technical University of Munich http://mips.gsf.de/staff/pagel -- http://mail.python.org/mailman/listinfo/python-list
Re: CSV(???)
David C. Ullrich <[EMAIL PROTECTED]> wrote: > Is there a csvlib out there somewhere? How about csv in the standard library? > (Um: Believe it or not I'm _still_ using > python 1.5.7. I have no idea if csv was part of the standard library backin those days... But even if not: either upgrade to something less outdated or see if you can get todays csv to work with the oldtimer. cu Philipp -- Dr. Philipp Pagel Tel. +49-8161-71 2131 Dept. of Genome Oriented BioinformaticsFax. +49-8161-71 2186 Technical University of Munich http://mips.gsf.de/staff/pagel -- http://mail.python.org/mailman/listinfo/python-list
Re: a=b change b a==b true??
[EMAIL PROTECTED] wrote: > I do not have a clue what is happening in the code below. > >>> a=[[2,4],[9,3]] > >>> b=a > >>> [map(list.sort,b)] > [[None, None]] > >>> b > [[2, 4], [3, 9]] > >>> a > [[2, 4], [3, 9]] > I want to make a copy of matrix a and then make changes to the > matrices separately. I assume that I am missing a fundamental > concept. The concept you are missing is the fact that b = a makes b another name for your nested list. As you correctly stated you really want a copy. This will do what you want: >>> import copy >>> a=[[2,4],[9,3]] >>> b = copy.deepcopy(a) >>> [map(list.sort,b)] [[None, None]] >>> a [[2, 4], [9, 3]] >>> b [[2, 4], [3, 9]] cu Philipp -- Dr. Philipp Pagel Tel. +49-8161-71 2131 Dept. of Genome Oriented BioinformaticsFax. +49-8161-71 2186 Technical University of Munich http://mips.gsf.de/staff/pagel -- http://mail.python.org/mailman/listinfo/python-list
Re: >>>> 911 operation by evil JEWS and Mossad <<<
On Nov 7, 4:08 pm, [EMAIL PROTECTED] wrote: > 911 carried out by evil jews and mossadhttp://www.guba.com/watch/2000991770 > > 911 truckload of Explosives on the George Washington > Bridgehttp://www.youtube.com/watch?v=J520P-MD9a0 > [...] I reported the first post in this thread (on Google groups) as abuse as its content is "false and defamatory". In addition to that, it has nothing to do with TeX. => Double reason to blaim the author! Please ignore threads like those in future and just report it! PN -- http://mail.python.org/mailman/listinfo/python-list
Re: How to pass shell variable to shell script from python
Gerardo Herzig <[EMAIL PROTECTED]> wrote: > Rockins Chen wrote: > Well, if you have to use os.system, that could be > os.system("export target=localhost.localdomain.org; ./callee.sh") Or os.system("env target=localhost.localdomain.org ./callee.sh") cu Philipp -- Dr. Philipp Pagel Lehrstuhl f. Genomorientierte Bioinformatik Technische Universität München http://mips.gsf.de/staff/pagel -- http://mail.python.org/mailman/listinfo/python-list
Re: rstrip error python2.4.3 not in 2.5.1?
dirkheld <[EMAIL PROTECTED]> wrote: > Here it is : I tought that I didn't matter because the deliciousapi > worked fine on my mac. > Traceback (most recent call last): > File "delgraph.py", line 62, in ? > url_metadata = d.get_url(site.rstrip()) > File "deliciousapi.py", line 269, in get_url > document.bookmarks = > self._extract_bookmarks_from_url_history(data) > File "deliciousapi.py", line 297, in > _extract_bookmarks_from_url_history > timestamp = datetime.datetime.strptime(month_string, '%b ‘ > %y') > AttributeError: type object 'datetime.datetime' has no attribute > 'strptime' The answer is right there: datetime.datetime has method strptime in python 2.5 but which was not available in 2.4. A quick look into the library reference confirms this: -- strptime( date_string, format) Return a datetime corresponding to date_string, parsed according to format. This is equivalent to datetime(*(time.strptime(date_string, format)[0:6])). ValueError is raised if the date_string and format can't be parsed by time.strptime() or if it returns a value which isn't a time tuple. New in version 2.5. -- cu Philipp -- Dr. Philipp Pagel Lehrstuhl f. Genomorientierte Bioinformatik Technische Universität München http://mips.gsf.de/staff/pagel -- http://mail.python.org/mailman/listinfo/python-list
Re: Delete hidden files on unix
loial <[EMAIL PROTECTED]> wrote: > How can I delete hidden files on unix with python, i.e I want to do > equivalent of > rm .lock* Here is one way to do it: import os, glob for filename in glob.glob('.lock*'): os.unlink(filename) Alternatively, you could also do this: import os os.system('rm .lock*') cu Philipp -- Dr. Philipp Pagel Lehrstuhl f. Genomorientierte Bioinformatik Technische Universität München http://mips.gsf.de/staff/pagel -- http://mail.python.org/mailman/listinfo/python-list
Re: Reading a file
zaheer.ag...@gmail.com wrote: > Hi > How do i read a file in Python and search a particular pattern > like I have a file char.txt which has > Mango=sweet > Sky=blue > I want to get the strings sweet and blue,How to do this..? If your entire file consists of such key=value pairs you may want to properly parse them: for lne in infile: line = line.rstrip() key, value = line.split('=') if key in ('Mango', 'Sky'): print value Or something like that - details depend on what exactly your criteria for picking the values are, of course. cu Philipp -- Dr. Philipp Pagel Lehrstuhl f. Genomorientierte Bioinformatik Technische Universität München http://mips.gsf.de/staff/pagel -- http://mail.python.org/mailman/listinfo/python-list
Re: Install modules with no root privilegies
Alfons Nonell-Canals <[EMAIL PROTECTED]> wrote: > Install python modules in a linux computer is really easy, it is because > the module is a package of the distribution or because the python > installation is really easy. But, in both situations, you need root > privilegies. > I would like to know how to install modules only for one user, with no > root privilegies. Do you know if it is possible and easy. Yes, there is. You can choose among two strategies referred to as "home scheme" and "prefix scheme" in the "Installing Python Modules" documentation: http://docs.python.org/install/index.html Have a look at Section 3 "Alternate installation". cu Philipp -- Dr. Philipp Pagel Lehrstuhl f. Genomorientierte Bioinformatik Technische Universität München http://mips.gsf.de/staff/pagel -- http://mail.python.org/mailman/listinfo/python-list
Convert IPv6 address to binary representation on 2.x/Windows
-BEGIN PGP SIGNED MESSAGE- Hash: SHA512 socket.inet_pton which does exactly what I want is not available on 2.x on Windows. Strangely, the documentation of socket.inet_aton (IPv4 only) reads: "inet_aton() does not support IPv6, and getnameinfo() should be used instead for IPv4/v6 dual stack support." Let's try that: >>> def gni(flag, addr="::1", port=80): ... try: ... res = socket.getnameinfo((addr,port), flag) ... except: ... res = "error" ... return res ... >>> [(ni,gni(socket.__dict__[ni])) for ni in filter(lambda k:k.startswith("NI_"), dir(socket))] [('NI_DGRAM', ('localhost', 'www')), ('NI_MAXHOST', 'error'), ('NI_MAXSERV', ('localhost', 'www')), ('NI_NAMEREQD', ('localhost', 'www')), ('NI_NOFQDN', ('localhost', 'www')), ('NI_NUMERICHOST', ('::1', 'www')), ('NI_NUMERICSERV', ('localhost', '80'))] >>> Neither of these values looks like 0x0001. Am I missing something or is the documentation just wrong? If so, how am I supposed to get a binary representation of an IPv6 address in the absence of socket.inet_pton? Should I write my I own version? -BEGIN PGP SIGNATURE- Version: GnuPG v1.4.9 (GNU/Linux) iEYEAREKAAYFAkmu5N4ACgkQ9eq1gvr7CFwNUgCdF4QdT2LlWWXNlKYbBvKEeTlh lDMAn2eGmFdx7rvM9+gr7tnHlENhgmq7 =Gsal -END PGP SIGNATURE- -- http://mail.python.org/mailman/listinfo/python-list
Re: Convert IPv6 address to binary representation on 2.x/Windows
-BEGIN PGP SIGNED MESSAGE- Hash: SHA512 Hi Martin, Martin v. Löwis wrote: > I do wonder why you need a binary representation of an IPv6 address... I'd like to subscribe to an IPv6 multicast address via socket.setsockopt(IPPROTO_IPV6, IPV6_JOIN_GROUP, binary_address). > Yes, writing your own routine is certainly an option. Is it the preferred one? Because I need this for two purposes: My own code as well as the python multicast example Demo/socket/mcast.py [1]. > Alternatively, > you can try one of the IP address manipulation libraries, such as > ipaddr, or netaddr. Disclaimer: I haven't checked whether these support > the requested functionality; please report back when you know. ipaddr[2] has functions that would certainly helpful (int(IP('::1')) yields 1), but not quite the one I'm looking for, although it would be trivial to write it. But then, why should I need ipaddr? netaddr[3] has the function I'm looking for Addr('::1').packed(), but it's way over the top for this purpose; an assembler implementation would be more readable. Kind regards, Philipp Hagemeister [1] http://bugs.python.org/issue5379 [2] http://ipaddr-py.googlecode.com [3] http://code.google.com/p/netaddr/ -BEGIN PGP SIGNATURE- Version: GnuPG v1.4.9 (GNU/Linux) iEYEAREKAAYFAkmu96cACgkQ9eq1gvr7CFzlAwCgrMXI6PVrBGXP5phvv2Fk//9b pQ0An37q6/KNZtIP4OvzYh68NXg4HCU4 =bNqC -END PGP SIGNATURE- -- http://mail.python.org/mailman/listinfo/python-list
Re: how to convert from network to host byte order
-BEGIN PGP SIGNED MESSAGE- Hash: SHA512 Evan wrote: >>> inp='\x04\x00' >>> out = socket.ntohs(struct.unpack('H',inp[:2])[0])) > Traceback (most recent call last): > File "", line 1, in > TypeError: argument 1 must be string or read-only buffer, not int Your approach is nearly right. First of all, you have to tell struct.unpack it should unpack from network order ("!"): >>> struct.unpack('!H', inp)[0] 1024 Then you want to repack it in host byte order. Use "=" for that. >>> out = struct.pack('=H', struct.unpack('!H', inp)[0]) >>> out '\x00\x04' For more information, look for "Size and alignment" in http://docs.python.org/library/struct.html. Regards, Philipp Hagemeister -BEGIN PGP SIGNATURE- Version: GnuPG v1.4.9 (GNU/Linux) iEYEAREKAAYFAkmv2JkACgkQ9eq1gvr7CFymKACghFXMZb9D6pkWZQdapvwTsKJ5 b0UAn0Uvbcguv/rdxjFKXhMQz22+Notn =ZiKx -END PGP SIGNATURE- -- http://mail.python.org/mailman/listinfo/python-list
Profiler throws NameError on any function
Hi, I'm trying to run the python profiler on some code but I always get NameErrors, even for the simplest case taken from the docs: import profile def foo(): a = 5 def prof(): profile.run('foo()') When I run prof() I get the following output: Traceback (most recent call last): File "", line 1, in File "dummy.py", line 11, in prof profile.run('foo()') File "/usr/lib/python2.5/profile.py", line 70, in run prof = prof.run(statement) File "/usr/lib/python2.5/profile.py", line 456, in run return self.runctx(cmd, dict, dict) File "/usr/lib/python2.5/profile.py", line 462, in runctx exec cmd in globals, locals File "", line 1, in NameError: name 'foo' is not defined The very same error I get using cProfile. It works when I call profile.runctx('foo()', globals(), locals()) which should be the same as run('foo()'), shouldn't it? I'm using python 2.5.2 on ubuntu 8.10. Cheers Phil -- http://mail.python.org/mailman/listinfo/python-list
Re: Binary IP address representation
-BEGIN PGP SIGNED MESSAGE- Hash: SHA512 Hi Dave, I've solved this now using ipaddr. ipaddr will be in the stdlib as soon as its developers realize there are actually not one, but two proposals to fix the remaining issues waiting for their input. Anyway, since ipaddr:r68, you can do the following: >>> import ipaddr >>> ipaddr.IP('::1').packed b'\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x01' Since you don't know or want to know the family in most use cases, this interface is actually nicer than that of inet_pton. For the record, here's how my compatibility function looks like. def _compat_ipaddr_inet_pton(family, addr): if family == socket.AF_INET: return ipaddr.IPv4(addr).packed elif family == socket.AF_INET6: return ipaddr.IPv6(addr).packed else: raise ValueError("Unknown protocol family " + family) Since socket.AF_INET6 will not be defined on old systems (are there any versions of Python 2.5+ that do not have that defined?), your solution is better for those (but needs netaddr, which is unlikely to enter stdlib soon). Thanks for sharing it. Regards, Philipp DrKJam wrote: > Hi, > > I've only just come across this thread this morning :- > > http://mail.python.org/pipermail/python-list/2009-March/703388.html > > Bit late to respond on this list so here is another option (if you are > still interested). > > Try the netaddr.fallback module :- > >>>> from netaddr.fallback import inet_pton, AF_INET6 >>>> inet_pton(AF_INET6, '::1') > \x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x01 > > It is self contained and written in pure Python. Forms part of the > latest 0.6.2 release of netaddr. > > Apologies the code in my project comes across as unreadable :-( > > Regards, > > Dave M. > -BEGIN PGP SIGNATURE- Version: GnuPG v1.4.9 (GNU/Linux) iEYEAREKAAYFAknu/zAACgkQ9eq1gvr7CFwUwwCfQLP+dnOdjn9JEttcaFQb5FH0 hLQAn33Lve8k/HXVsW0j7JZP3dL7897W =ki8e -END PGP SIGNATURE- -- http://mail.python.org/mailman/listinfo/python-list
.pth in current directory: Why doesn't it work as the documentation says?
Where is the fault in my reasoning here? 1) According to http://docs.python.org/dev/install/, "The most convenient way is to add a path configuration file to a directory that’s already on Python’s path, (...). 2) Path configuration files have an extension of .pth, (...)" 1&2 => 3) A file test.pth with the content "/example/" should result in sys.path containing "/example/". 4) "" (the current directory) is the first element of my sys.path 1&4 => 5) The current directory qualifies for "a directory that’s already on Python’s path," 1&3&5 => 6) echo /example/ > test.pth; python -c 'import sys;print(repr(sys.path))' should contain '/example'. I think I misinterpreted the documentation, but what exactly is wrong here? Regards, Philipp signature.asc Description: OpenPGP digital signature -- http://mail.python.org/mailman/listinfo/python-list
Re: .pth in current directory: Why doesn't it work as the documentation says?
David Lyon wrote: > (...) >> 1&2 => 3) A file test.pth with the content "/example/" should result in >> sys.path containing "/example/". > > No. Python, once finding the .pth will process it. Yes, but that processing will add /example/ to sys.path, right? >> 4) "" (the current directory) is the first element of my sys.path > > Not always - but maybe it is. Let's not assume anything. Of *my* sys.path. And by default, I think it is. > (...) >> I think I misinterpreted the documentation, but what exactly is wrong > here? > > What are you expecting? and maybe we can tell you why you aren't getting > it... > > David I'm expecting .pth files in the current directory to be be processed, according to docs/install/. Christian Heimes already pointed out this is not the case; so I'm wondering whether this is a mistake in the documentation or just my faulty logic. Cheers, Philipp signature.asc Description: OpenPGP digital signature -- http://mail.python.org/mailman/listinfo/python-list
Re: .pth in current directory: Why doesn't it work as the documentation says?
David Lyon wrote: > On Mon, 18 May 2009 14:34:33 +0200, Philipp Hagemeister > wrote: >> Yes, but that processing will add /example/ to sys.path, right? > > It actually works the other way around. The directories listed in > sys.path are scanned for .pth files. No, they are not. That's exactly my point. According to Christian Heimes, *some* of the directories listed in sys.path are scanned. "" is in sys.path, but is not scanned. > You can add packages by listing them inside a .PTH. > >> I'm expecting .pth files in the current directory to be be processed, >> according to docs/install/. Christian Heimes already pointed out this is >> not the case; so I'm wondering whether this is a mistake in the >> documentation or just my faulty logic. > > Perphaps you don't understand them yet. > > .PTH files are for adding run-time packages. > > May I ask why you are playing with .PTH files? they are a fairly > advanced sort of concept for describing where packages are located > to the python interpreter. > > If you are using .PTH files... you should be using "import .." > inside your code.. I know that, and I want to use them for an application consisting of multiple scripts, like so: / mylib/ somescripts/ script1.py script2.py mylib.pth (contains '../mylib/') otherscripts/ oscript1.py oscript2.py mylib.pth (contains '../mylib/') If you want, you can change the final point in my original post to: 1&3&5 => 6) echo /example/ > test.pth;touch /example/libfoo.py; python -c 'import libfoo' Cheers, Philipp signature.asc Description: OpenPGP digital signature -- http://mail.python.org/mailman/listinfo/python-list
Re: issue: Permissions in odfpy
Hi Shruti, your message is kind of hard to read. Please note the following: · Do not put useless junk("issue") in title. · Multiple exclamation marks convey a sure sign of a diseased mind, especially syntactically interesting constructions such as "??.." · You didn't purchase your keyboard in August 2001, did you? ( http://ars.userfriendly.org/cartoons/?id=20010820 ) · It's probably just me, but "so please give me some solution" sounds really rude. Why not "any ideas?", "thanks in advance" or just nothing? Would you answer an email that ended like this? Please keep in mind, you are not paying us, and we're trying to help you just because we want happy python users (or trying to offset us being evil at times). · Everyone mistpyes, and I'd be throwing mountains in my glass house if I complained about grammar, but please show at least some effort. That being said, this might help: import odf.opendocument doc = odf.opendocument.load('in.ods') # You may want to use another way to select the sheet, # this selects just the first one sheet = doc.spreadsheet.childNodes[0] sheet.setAttrNS( 'urn:oasis:names:tc:opendocument:xmlns:table:1.0', 'protected', 'true') doc.save('out.ods') Regards, Philipp shruti surve wrote: > hey, > i am using odfpy and generating spreadsheet in open office..but nobody > should modify the file..so can anybody tell me how can we give permissions > (read only) to spreadsheet in odfpy??..i have change the properties of my > normal open office spreadsheet file and made it read only..n also extracted > it..but in conteny.xml also i am not finding any property which can be used > in odfpy...so please give me some solution.. > > > regards > shruti surve > signature.asc Description: OpenPGP digital signature -- http://mail.python.org/mailman/listinfo/python-list
Re: identifying live hosts on a network
We acknowledge your problems with a network script idenifying live hosts on your network. Seriously, you have to tell us a little bit more so that we can help you. How about you actually post the script, and actually post the trouble (What exactly do you expect? What exactly do you see? What other steps have you tried?) Philipp hunteroakes...@gmail.com wrote: > HI > I am new to python and am having trouble coming up with a script that > idenifies all the live hosts on my network. > thanks Hunter signature.asc Description: OpenPGP digital signature -- http://mail.python.org/mailman/listinfo/python-list
Re: How to covert ASCII to integer in Python?
Skonieczny, Chris <[EMAIL PROTECTED]> wrote: > YOU SHOULD REMOVE or CORRECT YOUR POST here: > http://mail.python.org/pipermail/python-list/2007-February/427841.html > > It is not true - eg. try : > a='P'# P is ASCII , isn't it ? > b=int(a) > and what you will get ? An error !!! 'P' is obviously not an ASCII representation of a number. What did you expect? The closest number by visual appearance? cu Philipp -- Dr. Philipp Pagel Lehrstuhl f. Genomorientierte Bioinformatik Technische Universität München http://mips.gsf.de/staff/pagel -- http://mail.python.org/mailman/listinfo/python-list
Re: How to covert ASCII to integer in Python?
Mensanator <[EMAIL PROTECTED]> wrote: > On May 30, 10:03???am, Philipp Pagel <[EMAIL PROTECTED]> > wrote: > > 'P' is obviously not an ASCII representation of a number. > It is in base 36. Sure, but if that was the OP's intent he would most likely have mentioned it... As others have already guessed, it's most likely somethink like ord() he was after. cu Philipp -- Dr. Philipp Pagel Lehrstuhl f. Genomorientierte Bioinformatik Technische Universität München http://mips.gsf.de/staff/pagel -- http://mail.python.org/mailman/listinfo/python-list
Re: Graphs in Python
Sanhita Mallick <[EMAIL PROTECTED]> wrote: > I have looked at that, and other similar ones all of > which are based on Graphviz. Networkx is not based on graphviz. > My problem is that I myself am creating some large graphs [...] > So I would like to use a graphical/visual method than typing out the > nodes. Not sure what exactly you mean. you will have to enter the nodes somehow - afterwards you can visualize them. Do you mean you would like to have a GUI for entering nodes and edges? I see two options: (1) write a GUI to do that (2) use an existing graph editor and use networkx or something like that for analysis. > Also, I am looking for a good tutorial for basic graph > implementation other than the one on python.org. - Look at the source code for networkx. - Alternatively, basic graph algorithms can be found in many general algorithm books. - More specific stuff e.g. in A. Gibbons "Algorithmic Graph Theory". cu Philipp -- Dr. Philipp Pagel Lehrstuhl f. Genomorientierte Bioinformatik Technische Universität München http://mips.gsf.de/staff/pagel -- http://mail.python.org/mailman/listinfo/python-list
Re: Graphs in Python
greg_kr <[EMAIL PROTECTED]> wrote: > You should use Python with R. Google for Rpy, this is the best > Graphing you can do with Python The OP was refering to graph as in 'graph-theory', not plotting data. Of course, R has some packages for dealing with graphs in the former sense but I don't think that's a good solution to the OP's problem. cu Philipp -- Dr. Philipp Pagel Lehrstuhl f. Genomorientierte Bioinformatik Technische Universität München http://mips.gsf.de/staff/pagel -- http://mail.python.org/mailman/listinfo/python-list
Re: Python Success stories
azrael <[EMAIL PROTECTED]> wrote: > A friend of mine i a proud PERL developer which always keeps making > jokes on python's cost. There is only one sane way to deal with this situation: You need a common enemy. Java comes to mind ;-) cu Philipp -- Dr. Philipp Pagel Lehrstuhl f. Genomorientierte Bioinformatik Technische Universität München http://mips.gsf.de/staff/pagel -- http://mail.python.org/mailman/listinfo/python-list
Re: Renumbering
Francesco Pietra <[EMAIL PROTECTED]> wrote: > ATOM 3424 N LEU B 428 143.814 87.271 77.726 1.00115.20 > 2SG3426 > ATOM 3425 CA LEU B 428 142.918 87.524 78.875 1.00115.20 > 2SG3427 [...] > As you can see, the number of lines for a particular value in column 6 > changes from situation to situation, and may even be different for the > same name in column 4. For example, LEU can have a different number of > lines depending on the position of this amino acid (leucine). Others have alreade given good hints but I would like to add a bit of advice. The data you show appears to be a PDB protein structure file. It is important to realize that these are fixed-width files and columns can be empty so splitting on tab or whithespace will often fail. It is also important to know that the residue numbering (cols 23-26) is not necessarily contiguous and is not even unique without taking into account the 'insertion code' in column 27 which happens to be empty in your example. I would recommend to use a full-blown PDB parser to read the data and then iterate over the residues and do whatever you would like to acomplish that way. Biopython has such a parser: www.biopython.org cu Philipp -- Dr. Philipp Pagel Lehrstuhl f. Genomorientierte Bioinformatik Technische Universität München http://mips.gsf.de/staff/pagel -- http://mail.python.org/mailman/listinfo/python-list
Re: Creating a PYD file
Rony wrote: > Is a PYD file created from Pyrex faster in execution then a PYD file > created from python source ? What do you mean? An African or European swallow? Of course it depends on your choice of algorithm, programmer ability.familarity with the respective langugage, ... cu Philipp -- Dr. Philipp Pagel Lehrstuhl f. Genomorientierte Bioinformatik Technische Universität München http://webclu.bio.wzw.tum.de/~pagel/ -- http://mail.python.org/mailman/listinfo/python-list
Python3: hex() on arbitrary classes
class X(object): def __int__(self): return 42 def __hex__(self): return '2b' #sic hex(X()) What would you expect? Python2 returns '2b', but python 3(74624) throws TypeError: 'X' object cannot be interpreted as an integer. Why doesn't python convert the object to int before constructing the hex string? Regards, Philipp Hagemeister signature.asc Description: OpenPGP digital signature -- http://mail.python.org/mailman/listinfo/python-list
Re: Python3: hex() on arbitrary classes
Mark Dickinson wrote: > (...) If you want to be > able to interpret instances of X as integers in the various Python > contexts that expect integers (e.g., hex(), but also things like list > indexing), you should implement the __index__ method: Thanks. Somehow forgot this magic method and deleted it by accident. Philipp > > Python 3.2a0 (py3k:74624, Sep 1 2009, 16:53:00) > [GCC 4.3.2] on linux2 > Type "help", "copyright", "credits" or "license" for more information. >>>> class X: > ... def __index__(self): return 3 > ... >>>> hex(X()) > '0x3' >>>> range(10)[X()] > 3 >>>> 'abc' * X() > 'abcabcabc' > > -- > Mark signature.asc Description: OpenPGP digital signature -- http://mail.python.org/mailman/listinfo/python-list
convert char to byte representation
Hello, I am trying to xor the byte representation of every char in a string with its predecessor. But I don't know how to convert a char into its byte representation. This is to calculate the nmea checksum for gps data. e.g. everything between $ and * needs to be xor: $GPGSV,3,1,10,06,79,187,39,30,59,098,40,25,51,287,00,05,25,103,44* to get the checksum. Thank you for you help. Phil -- http://mail.python.org/mailman/listinfo/python-list
Store multiple dictionaries in a file
Hello, I would like to store multiple dictionaries in a file, if possible one per line. My code currently produces a new dictionary every iteration and passes it on to another peace of code. In order to be able to re-run some experiments at a later date I would like to store every dictionary in the same file. I looked at pickel, but that seems to require a whole file for each dictionary. It would be great if some one could tell me how to do that. Thank you, Phil -- http://mail.python.org/mailman/listinfo/python-list
Re: Store multiple dictionaries in a file
Thank you for you answer. > > I would like to store multiple dictionaries in a file, if possible one per > > line. > > Why "one per line" ? I agree with you that it sounds like nasty code :-) but there is a good reason for doing it this way - I think. My code collects data (attributes) of its current environment, e.g. date, time, location, etc. These values are put into a dictionary and passed to another program which processes the data. The dictionary (or vector of attributes) is the only interface between both progs. The one which creates the dictionary can forget about it after it has passed it on. This is where the storing comes into action. In order to be able to re-run an experiment I want to store the dictionaries in a file. Also the program might not run continuasly, therefore if I write all of them to a file, on after the other, I would be able to re-run the experiment much easier. Hope this makes sense. Thank you, Phil > > A pretty simple solution could be to store all the dicts in another > container (list or dict, depending on how you need to retrieve'em, but > from what you explain I'd say a list) and then pickle this container. -- http://mail.python.org/mailman/listinfo/python-list
Re: Store multiple dictionaries in a file
Hello, this is the solution I went for, as I am indeed not concernt about security and the implementation is straight forward. Thank you, Phil > If you're not worried about security, you could write the repr() of each > dict to the file and get the values back by using the eval() function. > repr() writes onto one line. > > If you're storing types without repr() representations this will not work. > > Jeremy -- http://mail.python.org/mailman/listinfo/python-list
passing arguments to a function - do I need type ?
Hello, I got a newbie question, I have written the following distance function: def distance(self,element1, element2): dist = 0 for n in range(len(element1)): dist = dist + pow((element1[n] - element2[n]),2) print 'dist' + dist return sqrt(dist) and in order to be able to use len() and index element1[] the function needs to know that the arguments element1 and element2 are both listst or doesn't it ? I get the following error msg: Traceback (most recent call last): File "Memory.py", line 105, in ? start.inputVector(inP2) File "Memory.py", line 97, in inputVector allDimensions[0].newAttribute(vector) File "Memory.py", line 56, in newAttribute dist = self.distance(n.getCenter,newElement) File "Memory.py", line 75, in distance for n in range(len(element1)): TypeError: len() of unsized object AND if I take len out I get: Traceback (most recent call last): File "Memory.py", line 105, in ? start.inputVector(inP2) File "Memory.py", line 97, in inputVector allDimensions[0].newAttribute(vector) File "Memory.py", line 56, in newAttribute dist = self.distance(n.getCenter,newElement) File "Memory.py", line 76, in distance dist = dist + pow((element1[n] - element2[n]),2) TypeError: unsubscriptable object Thank you very much for your help. Phil -- http://mail.python.org/mailman/listinfo/python-list
Re: passing arguments to a function - do I need type ?
Hello, thank you very much for all your help. I have solved the problem - you guys where right, the problem was some where else. I have another class which got an accessor: def getCenter(self): global center return center and I called it by saying n.getCenter, but this returns: > I changed it to n.getCenter() and now it works. Despite some small problems I am really getting to like python. Thank you, Phil On Sun, 10 Jul 2005, Paul McGuire wrote: > Is getCenter a function? If so, you need to invoke distance using: > dist = self.distance( n.getCenter(), newElement ) > > Of course, that is assuming that newElement is a local variable of type > list/tuple/etc. > > -- Paul > > -- http://mail.python.org/mailman/listinfo/python-list
Abstract methods in python - is this a good way ?)
Hello, I would like to use abstract methods in python to force some of the classes to implement common methods. I found this web page and wonder if it is a good way of implementing them: http://www.lychnis.net/blosxom/programming/python-abstract-methods-3.lychnis Also could some one please tell me what the type class is which class Metaclass (type): is inheriting from. Thank you, Phil -- http://mail.python.org/mailman/listinfo/python-list
wxPython Install
Hallo James I had the same problems. But I could solve them. The problem which is left: I do not know exaktly how I solved it. I have tried a lots of times, two weeks or fight against dependency-problems. In FedoraCore5 I did: yum update yum yum install python python-2.4.2-3.2.1 yum install python-devel python-devel-2.4.2-3.2.1 you need gtk+-1.2.10-50 and glib-1.2.10-18.2.2 which was already installed by FedoraCore5 with wxPython I had a lots of problems. Lots of tries to install from the tarball with lots of dependency-problems. http://www.wxpython.org/download.php Now I have got wxPython-2.6.3.2-1.fc5 installed, but, excuse me, I really don't know anymore what at least helped. Did you solve your problem? Because I am writing a documentation for wiki I could need your experience. Thanks Philipp -- http://mail.python.org/mailman/listinfo/python-list
Pyautogui troubles
Dear Python-Team, I have just repaired python after running my program which imports pyautogui, closing and reopening it and then getting this: ModuleNotFoundError: No module named „pyautogui“. Repairing didn’t work and I still get that message. All I did was closing the perfectly working program in 3.9.1 and reopening it in 3.9.1, but after the reopen I got the message. I’ve tried looking for solutions in at least seven developer forums, nothing worked. If it helps, I have Python 3.8 installed on my PC also. I hope you can fix my troubles. Thank you in advance, your help seeker. -- https://mail.python.org/mailman/listinfo/python-list
Selenium finds object that is interactible but says otherwise
Hello, I recently programmed some code for a webdriver with selenium. I asked the program to find an input tag, which is interactible, with this: searchbar=driver.find_element_by_class_name("ut-player-search-control--input-container") then i ask it to send keys, which has worked before too. But this is the message I get. And yes, i have checked, the input tag is the only tag with that class name, so there isn´t another tag which selenium could´ve interacted with. regards, me. -- https://mail.python.org/mailman/listinfo/python-list
Python cannot count apparently
Hello, I recently coded this snippet of code: myString=„hello“ for i in range(len(myString): print(string[i]) And now for the weird part: SOMETIMES, the output is this: hello And SOMETIMES, the output changes to: ohell WHY??? Why do I get different outputs with the EXACT SAME CODE? Can someone help me please? Thank you -- https://mail.python.org/mailman/listinfo/python-list
Troubles with Python imports
Hello, I’ve just typed „pip install selenium“ into my command prompt on windows 10. Although my computer told me that the requirement was already satisfied, import selenium did not work. So I tried different methods to install it and typed „Python“ in my command prompt and imported selenium. It worked fine. Then, I typed it into my shell and got an error. Why is it working in the command prompt but not in the actual shell? -- https://mail.python.org/mailman/listinfo/python-list