Search Results

Search found 14486 results on 580 pages for 'python idle'.

Page 15/580 | < Previous Page | 11 12 13 14 15 16 17 18 19 20 21 22  | Next Page >

  • Python - multithreading / multiprocessing, very strange problem.

    - by orokusaki
    import uuid import time import multiprocessing def sleep_then_write(content): time.sleep(5) print(content) if __name__ == '__main__': for i in range(15): p = multiprocessing.Process(target=sleep_then_write, args=('Hello World',)) p.start() print('Ah, what a hard day of threading...') This script output the following: Ah, what a hard day of threading... Ah, what a hard day of threading... Ah, what a hard day of threading... Ah, what a hard day of threading... Ah, what a hard day of threading... Ah, what a hard day of threading... Ah, what a hard day of threading... Ah, what a hard day of threading... Ah, what a hard day of threading... AAh, what a hard day of threading.. h, what a hard day of threading... Ah, what a hard day of threading... Ah, what a hard day of threading... Ah, what a hard day of threading... Ah, what a hard day of threading... Ah, what a hard day of threading... Hello World Hello World Hello World Hello World Hello World Hello World Hello World Hello World Hello World Hello World Hello World Hello World Hello World Hello World Hello World Firstly, why the heck did it print the bottom statement sixteen times (one for each process) instead of just the one time? Second, notice the AAh, and h, about half way down; that was the real output. This makes me wary of using threads ever, now. (Windows XP, Python 2.6.4, Core 2 Duo)

    Read the article

  • python-social-auth AuthCanceled exception

    - by vero4ka
    I'm using python-social-auth in my Django application for authentication via Facebook. But when a user tries to login and when it's been refirected to Facebook app page clicks on "Cancel" button, appears the following exception: ERROR 2014-01-03 15:32:15,308 base :: Internal Server Error: /complete/facebook/ Traceback (most recent call last): File "/home/vera/virtualenv/myapp/local/lib/python2.7/site-packages/django/core/handlers/base.py", line 114, in get_response response = wrapped_callback(request, *callback_args, **callback_kwargs) File "/home/vera/virtualenv/myapp/local/lib/python2.7/site-packages/django/views/decorators/csrf.py", line 57, in wrapped_view return view_func(*args, **kwargs) File "/home/vera/virtualenv/myapp/local/lib/python2.7/site-packages/social/apps/django_app/utils.py", line 45, in wrapper return func(request, backend, *args, **kwargs) File "/home/vera/virtualenv/myapp/local/lib/python2.7/site-packages/social/apps/django_app/views.py", line 21, in complete redirect_name=REDIRECT_FIELD_NAME, *args, **kwargs) File "/home/vera/virtualenv/myapp/local/lib/python2.7/site-packages/social/actions.py", line 54, in do_complete *args, **kwargs) File "/home/vera/virtualenv/myapp/local/lib/python2.7/site-packages/social/strategies/base.py", line 62, in complete return self.backend.auth_complete(*args, **kwargs) File "/home/vera/virtualenv/myapp/local/lib/python2.7/site-packages/social/backends/facebook.py", line 63, in auth_complete self.process_error(self.data) File "/home/vera/virtualenv/myapp/local/lib/python2.7/site-packages/social/backends/facebook.py", line 56, in process_error super(FacebookOAuth2, self).process_error(data) File "/home/vera/virtualenv/myapp/local/lib/python2.7/site-packages/social/backends/oauth.py", line 312, in process_error raise AuthCanceled(self, data.get('error_description', '')) AuthCanceled: Authentication process canceled Is the any way to catch it Django?

    Read the article

  • How to change a Linux user password from python

    - by Vaulor
    I'm having problems with changing a Linux user's password from python. I've tried so many things, but I couldn't manage to solve the issue, here is the sample of things I've already tried: sudo_password is the password for sudo, sudo_command is the command I want the system to run, user is get from a List and is the user who I want to change the password for, and newpass is the pass I want to assign to 'user' user = list.get(ANCHOR) sudo_command = 'passwd' f = open("passwordusu.tmp", "w") f.write("%s\n%s" % (newpass, newpass)) f.close() A=os.system('echo -e %s|sudo -S %s < %s %s' % (sudo_password, sudo_command,'passwordusu.tmp', user)) print A windowpass.destroy() 'A' is the return value for the execution of os.system, in this case 256. I tried also A=os.system('echo %s|sudo -S %s < %s %s' % (sudo_password, sudo_command,'passwordusu.tmp', user)) but it returns the same error code. I tried several other ways with 'passwd' command, but whithout succes. With 'chpasswd' command I 've tried this: user = list.get(ANCHOR) sudo_command = 'chpasswd' f = open("passwordusu.tmp", "w") f.write("%s:%s" % (user, newpass)) f.close() A=os.system('echo %s|sudo -S %s < %s %s' % (sudo_password, sudo_command,'passwordusu.tmp', user)) print A windowpass.destroy() also with: A=os.system('echo %s|sudo -S %s:%s|%s' % (sudo_password, user, newpass, sudo_command)) @;which returns 32512 A=os.system("echo %s | sudo -S %s < \"%s\"" % (sudo_password, sudo_command, "passwordusu.tmp")) @;which returns 256 I tried 'mkpasswd' and 'usermod' too like this: user = list.get(ANCHOR) sudo_command = 'mkpasswd -m sha-512' os.system("echo %s | sudo -S %s %s > passwd.tmp" % (sudo_password,sudo_command, newpass)) sudo_command="usermod -p" f = open('passwd.tmp', 'r') for line in f.readlines(): newpassencryp=line f.close() A=os.system("echo %s | sudo -S %s %s %s" % (sudo_password, sudo_command, newpassencryp, user)) @;which returns 32512 but, if you go to https://www.mkpasswd.net , hash the 'newpass' and substitute for 'newpassencryp', it returns 0 which theoretically means it has gone right, but so far it doesn't changes the password. I've searched on internet and stackoverflow for this issue or similar and tried what solutions exposed, but again,without success. I would really apreciate any help, and of course, if you need more info i'll be glad to supply it! Thanks in advance.

    Read the article

  • how to load files in python

    - by Alvaro
    I'm fairly new to python and would like some help on properly loading separate files. My codes purpose is to open a given file, search for customers of that file by the state or state abbreviation. However, i have a separate function to open a separate file where i have (name of state):(state abbreviation) Thanks. def file_state_search(fileid, state): z=0 indx = 0 while z<25: line=fileid.readline() data_list = ("Name:", "Address:", "City:", "State:", "Zipcode:") line_split = line.split(":") if state in line: while indx<5: print data_list[indx], line_split[indx] indx = indx + 1 elif state not in line: z = z + 1 def state_convert(fileid, state): line2=in_file2.readline() while state in line2: print line2 x=1 while x==1: print "Choose an option:" print print "Option '1': Search Record By State" print option = raw_input("Enter an option:") print if option == "1": state = raw_input("Enter A State:") in_file = open("AdrData.txt", 'r') line=in_file.readline() print in_file2 = open("States.txt", 'r') line2=in_file2.readline() converted_state = state_convert(in_file2, state) print converted_state state_find = file_state_search(in_file, state) print state_find x=raw_input("Enter '1' to continue, Enter '2' to stop: ") x=int(x) By the way, my first import statement works, for whatever reason my second one doesn't. Edit: My question is, what am i doing wrong in my state_convert function.

    Read the article

  • boost::python string-convertible properties

    - by Checkers
    I have a C++ class, which has the following methods: class Bar { ... const Foo& getFoo() const; void setFoo(const Foo&); }; where class Foo is convertible to std::string (it has an implicit constructor from std::string and an std::string cast operator). I define a Boost.Python wrapper class, which, among other things, defines a property based on previous two functions: class_<Bar>("Bar") ... .add_property( "foo", make_function( &Bar::getFoo, return_value_policy<return_by_value>()), &Bar::setFoo) ... I also mark the class as convertible to/from std::string. implicitly_convertible<std::string, Foo>(); implicitly_convertible<Foo, std::string>(); But at runtime I still get a conversion error trying to access this property: TypeError: No to_python (by-value) converter found for C++ type: Foo How to achieve the conversion without too much boilerplate of wrapper functions? (I already have all the conversion functions in class Foo, so duplication is undesirable.

    Read the article

  • Moving to an arbitrary position in a file in Python

    - by B Rivera
    Let's say that I routinely have to work with files with an unknown, but large, number of lines. Each line contains a set of integers (space, comma, semicolon, or some non-numeric character is the delimiter) in the closed interval [0, R], where R can be arbitrarily large. The number of integers on each line can be variable. Often times I get the same number of integers on each line, but occasionally I have lines with unequal sets of numbers. Suppose I want to go to Nth line in the file and retrieve the Kth number on that line (and assume that the inputs N and K are valid --- that is, I am not worried about bad inputs). How do I go about doing this efficiently in Python 3.1.2 for Windows? I do not want to traverse the file line by line. I tried using mmap, but while poking around here on SO, I learned that that's probably not the best solution on a 32-bit build because of the 4GB limit. And in truth, I couldn't really figure out how to simply move N lines away from my current position. If I can at least just "jump" to the Nth line then I can use .split() and grab the Kth integer that way. The nuance here is that I don't just need to grab one line from the file. I will need to grab several lines: they are not necessarily all near each other, the order in which I get them matters, and the order is not always based on some deterministic function. Any ideas? I hope this is enough information. Thanks!

    Read the article

  • Replacing a word in a text file with a value using python

    - by Jamde Jam
    I have been trying to replace a word in a text file with a value (say 1), but my outfile is blank.I am new to python (its only been a month since I have been learning it). My file is relatively large, but I just want to replace a word with the value 1 for now. Here is a segment of what the file looks like: NAME SECOND_1 ATOM 1 6 0 0 0 # ORB 1 ATOM 2 2 0 12/24 0 # ORB 2 ATOM 3 2 12/24 0 0 # ORB 2 ATOM 4 2 0 0 4/24 # ORB 3 ATOM 5 2 0 0 20/24 # ORB 3 ATOM 6 2 0 0 8/24 # ORB 3 ATOM 7 2 0 0 16/24 # ORB 3 ATOM 8 6 0 0 12/24 # ORB 1 ATOM 9 2 12/24 0 12/24 # ORB 2 ATOM 10 2 0 12/24 12/24 # ORB 2 #1 #2 #3 I want to first replace the word ATOM with the value 1. Next I want to replace #ORB with a space. Here is what I am trying thus far. input = open('SECOND_orbitsJ22.txt','r') output=open('SECOND_orbitsJ22_out.txt','w') for line in input: word=line.split(',') if(word[0]=='ATOM'): word[0]='1' output.write(','.join(word)) Can anyone offer any suggestions or help? Thanks so much.

    Read the article

  • Supersede users need to press enter after inputting a string in python 3.0

    - by Cimex
    I've been attempting to create a simple Rock, Paper, Scissors game in python 3.0 -- very standard task for anybody learning programming. But, as I finish up to a point, I think,"wow, that'd be awesome", or,"it'd be cool to do this!" So anyways, I keep building upon the project... I've developed a menu, a single player game vs the computer, and just finished the multiplayer game. But, I've realized, that the multiplayer game isn't very effective. It just dosen't work like the analog version of the game. Currently, it'll ask for player1's input, then player2's input, compare them, and spit out the result and the current score. What I'd rather have happen is that the program asks for both players input at the same time and both players input their choice at the same time. I understand that I can easily do that by just grabbing the index of the first and second answer and compare the 2 inputs -- easy. But what I'd rather have happen is that after both players enter their one character answers at the same time (r for rock, p for paper, or s for scissors), then the program will auto enter the input. Not needing someone to press enter. The input would be dictated by the fact that 2 characters have been entered. I guess my question is: Is there any way to dictate what can be used as an input for 'enter'?

    Read the article

  • Learning Python else syntax error

    - by user1441016
    Hi I am learning python by doing the practice problems for Open course at MIT 6.00 Intro to Computer Science. I am Trying to do practice problem 1 part 2 create a recursive function to count the instance of key in target. My code so far... from string import * def countSubStringMatchRecursive (target, key,x,s): if (find(target,key)==find(target,key,s)) and (find(target,key)==find(target,key,(find(target,key)))):#if first and last return (1) elif (find(target,key)==find(target,key,s))and (find(target,key)!=find(target,key,(find(target,key)))):#if first but not last x=1 s= find(target,key) return (countSubStringMatchRecursive(target,key,s,x) elif (find(target,key,s))==-1 and (find(target,key)!=find(target,key,s)):#if last but not first return (x+1) elif:(find(target,key,s))!=-1 and (find(target,key)!=find(target,key,s)):#if not last and not first x=x+1 s= find(target,key,s) return (countSubStringMatchRecursive(target,key,s,x) I getting a syntax error at line 8. I would just like to know what I did wrong there. Dont worry about the other mistakes I should be able to get those sorted out. I just Stuck on this. Thanks.

    Read the article

  • Python OOP - object has no attribute

    - by user1744269
    I am attempting to learn how to program. I really do want to learn how to program; I love the building and design aspect of it. However, in Java and Python, I have tried and failed with programs as they pertain to objects, classes, methods.. I am trying to develop some code for a program, but im stumped. I know this is a simple error. However I am lost! I am hoping someone can guide me to a working program, but also help me learn (criticism is not only expected, but APPRECIATED). class Converter: def cTOf(self, numFrom): numFrom = self.numFrom numTo = (self.numFrom * (9/5)) + 32 print (str(numTo) + ' degrees Farenheit') return numTo def fTOc(self, numFrom): numFrom = self.numFrom numTo = ((numFrom - 32) * (5/9)) return numTo convert = Converter() numFrom = (float(input('Enter a number to convert.. '))) unitFrom = input('What unit would you like to convert from.. ') unitTo = input('What unit would you like to convert to.. ') if unitFrom == ('celcius'): convert.cTOf(numFrom) print(numTo) input('Please hit enter..') if unitFrom == ('farenheit'): convert.fTOc(numFrom) print(numTo) input('Please hit enter..')

    Read the article

  • How could there still not be a mysqldb module for Python 3? [closed]

    - by itsadok
    This SO question is now more than two years old. MySQL is an incredibly popular database engine, Python is an incredibly popular programming language, and Python 3 has been officially released two years ago, and was available even before that. What's more, the whole mysqldb module is just a layer translating Python's db-api to MySQL's API. It's not that big of a library. I must be missing something here. How come almost* nobody in the entire open source community has spent the (I'm guessing) two weeks it takes to port this lib? Is Python 3 that unpopular? Is the combination of python and mysql not as common as I assume? Or maybe it's just a lot harder to port mysqldb than I assume? Anyone know the inside story on this? * Now I see that this guy has done it, which takes some of the wind out of my question, but it still seems to little and too late to make sense. EDIT: OK, I'm aware that the stock answers for these kind of questions cover this one as well. Patches welcome, scratch your itch, we don't work for you and we don't have the time, etc. I actually took a shot at porting this about a year ago, but it was my first time doing anything with Python C extensions, and I failed. My point in writing this was not a plea for somebody to write it, but genuine curiosity: it seems that some much more complicated libraries have been ported to python 3 already, and in the poll for which libraries should be ported, mysqldb is not even nominated! That suggests that maybe (2) is the right answer. UPDATE: I found that there are several new libraries that provide mysql support under Python 3, I just wasn't googling hard enough. That explains everything.

    Read the article

  • Does python import all the listed libraries? - Python

    - by RadiantHex
    Hi folks, I'm just wondering, I often have really long python files and imports tend to stack quite quickly. PEP8 says that the imports should always be written at the beginning of the file. Do all the imported libraries get imported when calling a function coded in the file? Or do only the necessary libraries get called? Does it make sense to worry about this? Is there no reason to import libraries within the functions or classes that need them?

    Read the article

  • Replacing words in string

    - by abkai
    Okay, so I have the following little function: def swap(inp): inp = inp.split() out = "" for item in inp: ind = inp.index(item) item = item.replace("i am", "you are") item = item.replace("you are", "I am") item = item.replace("i'm", "you're") item = item.replace("you're", "I'm") item = item.replace("my", "your") item = item.replace("your", "my") item = item.replace("you", "I") item = item.replace("my", "your") item = item.replace("i", "you") inp[ind] = item for item in inp: ind = inp.index(item) item = item + " " inp[ind] = item return out.join(inp) Which, while it's not particularly efficient gets the job done for shorter sentences. Basically, all it does is swaps pronoun etc. perspectives. This is fine when I throw a string like "I love you" at it, it returns "you love me" but when I throw something like: you love your version of my couch because I love you, and you're a couch-lover. I get: I love your versyouon of your couch because I love I, and I'm a couch-lover. I'm confused as to why this is happening. I explicitly split the string into a list to avoid this. Why would it be able to detect it as being a part of a list item, rather than just an exact match? Also, slightly deviating to avoid having to post another question so similar; if a solution to this breaks this function, what will happen to commas, full stops, other punctuation? It made some very surprising mistakes. My expected output is: I love my version of your couch because you love I, and I'm a couch-lover. The reason I formatted it like this, is because I eventually hope to be able to replace the item.replace(x, y) variables with words in a database.

    Read the article

  • It says i have an indented block when i dont?

    - by user3728373
    def cave(): global key global response print(''' You find yourself standing infront of a cave. You venture into the cave to find a large door blocking your path. (insert key, turn around''') response = input("Enter a command: ") while response != 'insert key' or response != 'turn around': if response =='insert key' or response == 'turn around': break print('Choose one of the options: ") response = input() if response == 'insert key': if key == 1: win() else: print('''You don't have a key. Get One!!''') elif response == 'turn around' : home()

    Read the article

  • Python — Time complexity of built-in functions versus manually-built functions in finite fields

    - by stackuser
    Generally, I'm wondering about the advantages versus disadvantages of using the built-in arithmetic functions versus rolling your own in Python. Specifically, I'm taking in GF(2) finite field polynomials in string format, converting to base 2 values, performing arithmetic, then output back into polynomials as string format. So a small example of this is in multiplication: Rolling my own: def multiply(a,b): bitsa = reversed("{0:b}".format(a)) g = [(b<<i)*int(bit) for i,bit in enumerate(bitsa)] return reduce(lambda x,y: x+y,g) Versus the built-in: def multiply(a,b): # a,b are GF(2) polynomials in binary form .... return a*b #returns product of 2 polynomials in gf2 Currently, operations like multiplicative inverse (with for example 20 bit exponents) take a long time to run in my program as it's using all of Python's built-in mathematical operations like // floor division and % modulus, etc. as opposed to making my own division, remainder, etc. I'm wondering how much of a gain in efficiency and performance I can get by building these manually (as shown above). I realize the gains are dependent on how well the manual versions are built, that's not the question. I'd like to find out 'basically' how much advantage there is over the built-in's. So for instance, if multiplication (as in the example above) is well-suited for base 10 (decimal) arithmetic but has to jump through more hoops to change bases to binary and then even more hoops in operating (so it's lower efficiency), that's what I'm wondering. Like, I'm wondering if it's possible to bring the time down significantly by building them myself in ways that maybe some professionals here have already come across.

    Read the article

  • Newbie, deciding Python or Erlang

    - by Joe
    Hi Guys, I'm a Administrator (unix, Linux and some windows apps such as Exchange) by experience and have never worked on any programming language besides C# and scripting on Bash and lately on powershell. I'm starting out as a service provider and using multiple network/server monitoring tools based on open source (nagios, opennms etc) in order to monitor them. At this moment, being inspired by a design that I came up with, to do more than what is available with the open source at this time, I would like to start programming and test some of these ideas. The requirement is that a server software that captures a stream of data and store them in a database(CouchDB or MongoDB preferably) and the client side (agent installed on a server) would be sending this stream of data on a schedule of every 10 minutes or so. For these two core ideas, I have been reading about Python and Erlang besides ruby. I do plan to use either Amazon or Rackspace where the server platform would run. This gives me the scalability needed when we have more customers with many servers. For that reason alone, I thought Erlang was a better fit(I could be totally wrong, new to this game) and I understand that Erlang has limited support in some ways compared to Ruby or Python. But also I'm totally new to the programming realm of things and any advise would be appreciated grately. Jo

    Read the article

  • Where can I find out the following info on python (coming from Ruby)

    - by Michael Durrant
    I'm coming from Ruby and Ruby on Rails to Python. Where can I find or find resources about: The command prompt, what is python's version of 'irb' django, what is a good resource for installing, using, etc. pythoncasts... is there anything like railscats, i.e. good video tutorials web sites with the api info about what version have what and which to use. info and recommendations on editors, plugins and IDE's common gotchas for newbies and good things to know at the outset scaling issues, common reasons what is the equivalent of 'gems', i.e. components I can plug in what are popular plugins for django authentication and forms similar to devise and simple_form testing, what's available, anything similar to rspec? database adapters - any preferences? framework info - is django MVC like rails? OO'yness. Is everything an object that gets send messages? Different paradign? syntax - anything like jslint for checking for well-formed code?

    Read the article

  • python: os.system does not execute shell comand

    - by capoluca
    I need to execute shell command in python program (I have ubuntu). More specifically I want to create graph using graphviz in python script. My code is os.system("dot -Tpng graph.dot -o graph.png") It does not work, but if I just type dot -Tpng graph.dot -o graph.png in command line then everything is fine. Do you know what the problem? Thank you! Edit: Does not work means that nothing happens, there are no errors. Output from dot -v -Tpng graph.dot -o graph.png: dot - graphviz version 2.26.3 (20100126.1600) Activated plugin library: libgvplugin_pango.so.6 Using textlayout: textlayout:cairo Activated plugin library: libgvplugin_dot_layout.so.6 Using layout: dot:dot_layout Using render: cairo:cairo Using device: png:cairo:cairo The plugin configuration file: /usr/lib/graphviz/config6 was successfully loaded. render : cairo dot fig gd map ps svg tk vml vrml xdot layout : circo dot fdp neato nop nop1 nop2 osage patchwork sfdp twopi textlayout : textlayout device : canon cmap cmapx cmapx_np dot eps fig gd gd2 gif gv imap imap_np ismap jpe jpeg jpg pdf plain plain-ext png ps ps2 svg svgz tk vml vmlz vrml wbmp x11 xdot xlib loadimage : (lib) eps gd gd2 gif jpe jpeg jpg png ps svg

    Read the article

  • Ruby or Python?

    - by Bobby Tables
    Hi all, This question is extremely subjective and open-ended. It might even sound like something I should just research for myself and make my own decision. But I'd like to put it out there and get some thoughts from others. Long story short - I burned out with the rat race and am on a self-funded sabbatical this year. Much of it is to take a break from the corporate grind and travel around, but I also want to play around with new technologies and do some self-learning projects, to stay up to speed on programming, and well - I just love tinkering with programming, when there's no pressure! Here's the thing: I am a lifetime C/C++/Java programmer. I'm a bit of a squiggly bracket snob since I've been working with this family of languages for my entire programming career. So I'd like to learn a language which isn't so closely syntactically related to this group. What I'm basically looking for is a language which is relatively general purpose, fun to learn, has some new concepts that are different from C++/Java, and has a good community. A secondary consideration is that it has good web development frameworks. A tertiary consideration is that it's not totally academic (read: there are real world jobs out there using it). I've narrowed it down to Ruby or Python. My impression of Ruby is that it is extremely web oriented - that the only real application of it is as a server side scripting language for doing web stuff (mainly Ruby on Rails). For Python I'm not so sure. TL;DR and to put it as succinctly as possible: which of these would be better for a C++/Java guy to learn to get some new perspectives on programming? And which is more open and general purpose and applicable to a wider set of applications? I'm leaning towards Ruby at the moment, but I worry to an extent that it looks like it's used as nothing but a server side web language.

    Read the article

  • How to distribute python GTK applications?

    - by Nik
    This is in correlation with the previous question I asked here. My aim is to create and package an application for easy installation in Ubuntu and other debian distributions. I understand that the best way to do this is by creating .deb file with which users can easily install my application on their system. However, I would also like to make sure my application is available in multiple languages. This is why I raised the question before which you can read here. In the answers that were provided, I was asked to use disutils for my packaging. I am however missing the bigger picture here. Why is there a need to include a setup.py file when I distribute my application in .deb format? My purpose is to ensure that users do not need to perform python setup.py to install my application but rather just click on the .deb file. I already know how to create a deb file from the excellent tutorial available here. It clearly shows how to edit rules, changelog and everything required to create a clean deb file. You can look at my application source code and folder structure at Github if it helps you better understand my situation. Please note I have glanced through the official python documentation found here. But I am hoping that I would get an answer which would help even a lame man understand since my knowledge is pretty poor in this regard.

    Read the article

  • Strategies for managUse of types in Python

    - by dave
    I'm a long time programmer in C# but have been coding in Python for the past year. One of the big hurdles for me was the lack of type definitions for variables and parameters. Whereas I totally get the idea of duck typing, I do find it frustrating that I can't tell the type of a variable just by looking at it. This is an issue when you look at someone else's code where they've used ambiguous names for method parameters (see edit below). In a few cases, I've added asserts to ensure parameters comply with an expected type but this goes against the whole duck typing thing. On some methods, I'll document the expected type of parameters (eg: list of user objects), but even this seems to go against the idea of just using an object and let the runtime deal with exceptions. What strategies do you use to avoid typing problems in Python? Edit: Example of the parameter naming issues: If our code base we have a task object (ORM object) and a task_obj object (higher level object that embeds a task). Needless to say, many methods accept a parameter named 'task'. The method might expect a task or a task_obj or some other construct such as a dictionary of task properties - it is not clear. It is them up to be to look at how that parameter is used in order to work out what the method expects.

    Read the article

  • Strategies for managing use of types in Python

    - by dave
    I'm a long time programmer in C# but have been coding in Python for the past year. One of the big hurdles for me was the lack of type definitions for variables and parameters. Whereas I totally get the idea of duck typing, I do find it frustrating that I can't tell the type of a variable just by looking at it. This is an issue when you look at someone else's code where they've used ambiguous names for method parameters (see edit below). In a few cases, I've added asserts to ensure parameters comply with an expected type but this goes against the whole duck typing thing. On some methods, I'll document the expected type of parameters (eg: list of user objects), but even this seems to go against the idea of just using an object and let the runtime deal with exceptions. What strategies do you use to avoid typing problems in Python? Edit: Example of the parameter naming issues: If our code base we have a task object (ORM object) and a task_obj object (higher level object that embeds a task). Needless to say, many methods accept a parameter named 'task'. The method might expect a task or a task_obj or some other construct such as a dictionary of task properties - it is not clear. It is them up to be to look at how that parameter is used in order to work out what the method expects.

    Read the article

  • matplotlib and python multithread file processing

    - by Napseis
    I have a large number of files to process. I have written a script that get, sort and plot the datas I want. So far, so good. I have tested it and it gives the desired result. Then I wanted to do this using multithreading. I have looked into the doc and examples on the internet, and using one thread in my program works fine. But when I use more, at some point I get random matplotlib error, and I suspect some conflict there, even though I use a function with names for the plots, and iI can't see where the problem could be. Here is the whole script should you need more comment, i'll add them. Thank you. #!/usr/bin/python import matplotlib matplotlib.use('GTKAgg') import numpy as np from scipy.interpolate import griddata import matplotlib.pyplot as plt import matplotlib.colors as mcl from matplotlib import rc #for latex import time as tm import sys import threading import Queue #queue in 3.2 and Queue in 2.7 ! import pdb #the debugger rc('text', usetex=True)#for latex map=0 #initialize the map index. It will be use to index the array like this: array[map,[x,y]] time=np.zeros(1) #an array to store the time middle_h=np.zeros((0,3)) #x phi c #for the middle of the box current_file=open("single_void_cyl_periodic_phi_c_middle_h_out",'r') for line in current_file: if line.startswith('# === time'): map+=1 np.append(time,[float(line.strip('# === time '))]) elif line.startswith('#'): pass else: v=np.fromstring(line,dtype=float,sep=' ') middle_h=np.vstack( (middle_h,v[[1,3,4]]) ) current_file.close() middle_h=middle_h.reshape((map,-1,3)) #3d array: map, x, phi,c ##### def load_and_plot(): #will load a map file, and plot it along with the corresponding profile loaded before while not exit_flag: print("fecthing work ...") #try: if not tasks_queue.empty(): map_index=tasks_queue.get() print("----> working on map: %s" %map_index) x,y,zp=np.loadtxt("single_void_cyl_growth_periodic_post_map_"+str(map_index),unpack=True, usecols=[1, 2,3]) for i,el in enumerate(zp): if el<0.: zp[i]=0. xv=np.unique(x) yv=np.unique(y) X,Y= np.meshgrid(xv,yv) Z = griddata((x, y), zp, (X, Y),method='nearest') figure=plt.figure(num=map_index,figsize=(14, 8)) ax1=plt.subplot2grid((2,2),(0,0)) ax1.plot(middle_h[map_index,:,0],middle_h[map_index,:,1],'*b') ax1.grid(True) ax1.axis([-15, 15, 0, 1]) ax1.set_title('Profiles') ax1.set_ylabel(r'$\phi$') ax1.set_xlabel('x') ax2=plt.subplot2grid((2,2),(1,0)) ax2.plot(middle_h[map_index,:,0],middle_h[map_index,:,2],'*r') ax2.grid(True) ax2.axis([-15, 15, 0, 1]) ax2.set_ylabel('c') ax2.set_xlabel('x') ax3=plt.subplot2grid((2,2),(0,1),rowspan=2,aspect='equal') sub_contour=ax3.contourf(X,Y,Z,np.linspace(0,1,11),vmin=0.) figure.colorbar(sub_contour,ax=ax3) figure.savefig('single_void_cyl_'+str(map_index)+'.png') plt.close(map_index) tasks_queue.task_done() else: print("nothing left to do, other threads finishing,sleeping 2 seconds...") tm.sleep(2) # except: # print("failed this time: %s" %map_index+". Sleeping 2 seconds") # tm.sleep(2) ##### exit_flag=0 nb_threads=2 tasks_queue=Queue.Queue() threads_list=[] jobs=list(range(map)) #each job is composed of a map print("inserting jobs in the queue...") for job in jobs: tasks_queue.put(job) print("done") #launch the threads for i in range(nb_threads): working_bee=threading.Thread(target=load_and_plot) working_bee.daemon=True print("starting thread "+str(i)+' ...') threads_list.append(working_bee) working_bee.start() #wait for all tasks to be treated tasks_queue.join() #flip the flag, so the threads know it's time to stop exit_flag=1 for t in threads_list: print("waiting for threads %s to stop..."%t) t.join() print("all threads stopped")

    Read the article

< Previous Page | 11 12 13 14 15 16 17 18 19 20 21 22  | Next Page >