Q_CreationDate
stringlengths
23
23
Title
stringlengths
11
149
Question
stringlengths
25
6.53k
Answer
stringlengths
15
5.1k
Score
float64
-1
1.2
Is_accepted
bool
2 classes
N_answers
int64
1
17
Q_Id
int64
0
6.76k
2009-07-14 20:29:34.933
Python object has no referrers but still accessible via a weakref?
Should it be possible for gc.get_referrers(obj) to return an empty list for an object, but the object still be accessible through a weak reference? If so how would I start trying to identify the cause for this object not being garbage collected? Edit: I'm not sure exactly how a code sample would help in this case - there's obviously a strong reference somewhere, but I'll be damned if I can find it. I was of the impression that all strong references to an object would be identified by get_referrers(). Edit: Solved. I found the variable with a strong reference - It was inside the game event loop but wasn't a class variable so get_referrers wasn't picking it up.
I am glad you have found your problem, unrelated to the initial question. Nonetheless, I have a different take on the answer for posterity, in case others have the problem. It IS legal for the object to have no referrers and yet not be garbage collected. From the Python 2.7 manual: "An implementation is allowed to postpone garbage collection or omit it altogether — it is a matter of implementation quality how garbage collection is implemented, as long as no objects are collected that are still reachable." The NO-OP garbage collector is legal. The discussions about generational and reference-counting garbage collectors are referring to a particular CPython implementation (as tagged in the question)
0.081452
false
2
217
2009-07-14 20:29:34.933
Python object has no referrers but still accessible via a weakref?
Should it be possible for gc.get_referrers(obj) to return an empty list for an object, but the object still be accessible through a weak reference? If so how would I start trying to identify the cause for this object not being garbage collected? Edit: I'm not sure exactly how a code sample would help in this case - there's obviously a strong reference somewhere, but I'll be damned if I can find it. I was of the impression that all strong references to an object would be identified by get_referrers(). Edit: Solved. I found the variable with a strong reference - It was inside the game event loop but wasn't a class variable so get_referrers wasn't picking it up.
It might also be the case that a reference was leaked by a buggy C extension, IMHO you will not see the referer, yet still the refcount does not go down to 0. You might want to check the return value of sys.getrefcount.
0.081452
false
2
217
2009-07-15 03:15:27.133
creating non-reloading dynamic webapps using Django
As far as I know, for a new request coming from a webapp, you need to reload the page to process and respond to that request. For example, if you want to show a comment on a post, you need to reload the page, process the comment, and then show it. What I want, however, is I want to be able to add comments (something like facebook, where the comment gets added and shown without having to reload the whole page, for example) without having to reload the web-page. Is it possible to do with only Django and Python with no Javascript/AJAX knowledge? I have heard it's possible with AJAX (I don't know how), but I was wondering if it was possible to do with Django. Thanks,
Maybe a few iFrames and some Comet/long-polling? Have the comment submission in an iFrame (so the whole page doesn't reload), and then show the result in the long-polled iFrame... Having said that, it's a pretty bad design idea, and you probably don't want to be doing this. AJAX/JavaScript is pretty much the way to go for things like this. I have heard it's possible with AJAX...but I was wondering if it was possible to do with Django. There's no reason you can't use both - specifically, AJAX within a Django web application. Django provides your organization and framework needs (and a page that will respond to AJAX requests) and then use some JavaScript on the client side to make AJAX calls to your Django-backed page that will respond correctly. I suggest you go find a basic jQuery tutorial which should explain enough basic JavaScript to get this working.
0.101688
false
2
218
2009-07-15 03:15:27.133
creating non-reloading dynamic webapps using Django
As far as I know, for a new request coming from a webapp, you need to reload the page to process and respond to that request. For example, if you want to show a comment on a post, you need to reload the page, process the comment, and then show it. What I want, however, is I want to be able to add comments (something like facebook, where the comment gets added and shown without having to reload the whole page, for example) without having to reload the web-page. Is it possible to do with only Django and Python with no Javascript/AJAX knowledge? I have heard it's possible with AJAX (I don't know how), but I was wondering if it was possible to do with Django. Thanks,
You want to do that with out any client side code (javascript and ajax are just examples) and with out reloading your page (or at least part of it)? If that is your question, then the answer unfortunately is you can't. You need to either have client side code or reload your page. Think about it, once the client get's the page it will not change unless The client requests the same page from the server and the server returns and updated one the page has some client side code (eg: javascript) that updates the page. I can not imagine a third possibility. I have not coded in Django for more than 30 mins and this is clearly obvious to me. If I am wrong plz down vote :D
1.2
true
2
218
2009-07-17 22:18:26.670
How to override Py_GetPrefix(), Py_GetPath()?
I'm trying to embed the Python interpreter and need to customize the way the Python standard library is loaded. Our library will be loaded from the same directory as the executable, not from prefix/lib/. We have been successful in making this work by manually modifying sys.path after calling Py_Initialize(), however, this generates a warning because Py_Initialize is looking for site.py in ./lib/, and it's not present until after Py_Initialize has been called and we have updated sys.path. The Python c-api docs hint that it's possible to override Py_GetPrefix() and Py_GetPath(), but give no indication of how. Does anyone know how I would go about overriding them?
Have you considered using putenv to adjust PYTHONPATH before calling Py_Initialize?
0.386912
false
2
219
2009-07-17 22:18:26.670
How to override Py_GetPrefix(), Py_GetPath()?
I'm trying to embed the Python interpreter and need to customize the way the Python standard library is loaded. Our library will be loaded from the same directory as the executable, not from prefix/lib/. We have been successful in making this work by manually modifying sys.path after calling Py_Initialize(), however, this generates a warning because Py_Initialize is looking for site.py in ./lib/, and it's not present until after Py_Initialize has been called and we have updated sys.path. The Python c-api docs hint that it's possible to override Py_GetPrefix() and Py_GetPath(), but give no indication of how. Does anyone know how I would go about overriding them?
You could set Py_NoSiteFlag = 1, call PyInitialize and import site.py yourself as needed.
1.2
true
2
219
2009-07-20 05:00:42.560
tkMessageBox
Can anybody help me out in how to activate 'close' button of askquestion() of tkMessageBox??
By 'activate', do you mean make it so the user can close the message box by clicking the close ('X') button? I do not think it is possible using tkMessageBox. I guess your best bet is to implement a dialog box with this functionality yourself. BTW: What should askquestion() return when the user closes the dialog box?
1.2
true
1
220
2009-07-20 19:38:26.637
Django, how to make a view atomic?
I have a simple django app to simulate a stock market, users come in and buy/sell. When they choose to trade, the market price is read, and based on the buy/sell order the market price is increased/decreased. I'm not sure how this works in django, but is there a way to make the view atomic? i.e. I'm concerned that user A's actions may read the price but before it's updated because of his order, user B's action reads the price. Couldn't find a simple, clean solution for this online. Thanks.
Wrap the DB queries that read and the ones that update in a transaction. The syntax depends on what ORM you are using.
-0.135221
false
1
221
2009-07-21 20:28:25.470
how do I read everything currently in a subprocess.stdout pipe and then return?
I'm using python's subprocess module to interact with a program via the stdin and stdout pipes. If I call the subprocesses readline() on stdout, it hangs because it is waiting for a newline. How can I do a read of all the characters in the stdout pipe of a subprocess instance? If it matters, I'm running in Linux.
You should loop using read() against a set number of characters.
0.386912
false
1
222
2009-07-22 19:26:48.607
In Python, how do I indicate I'm overriding a method?
In Java, for example, the @Override annotation not only provides compile-time checking of an override but makes for excellent self-documenting code. I'm just looking for documentation (although if it's an indicator to some checker like pylint, that's a bonus). I can add a comment or docstring somewhere, but what is the idiomatic way to indicate an override in Python?
Python ain't Java. There's of course no such thing really as compile-time checking. I think a comment in the docstring is plenty. This allows any user of your method to type help(obj.method) and see that the method is an override. You can also explicitly extend an interface with class Foo(Interface), which will allow users to type help(Interface.method) to get an idea about the functionality your method is intended to provide.
0.135221
false
1
223
2009-07-22 22:05:47.193
Recommended ways to split some functionality into functions, modules and packages?
There comes a point where, in a relatively large sized project, one need to think about splitting the functionality into various functions, and then various modules, and then various packages. Sometimes across different source distributions (eg: extracting a common utility, such as optparser, into a separate project). The question - how does one decide the parts to put in the same module, and the parts to put in a separate module? Same question for packages.
I sympathize with you. You are suffering from self-doubt. Don't worry. If you can speak any language, including your mother tongue, you are qualified to do modularization on your own. For evidence, you may read "The Language Instinct," or "The Math Instinct." Look around, but not too much. You can learn a lot from them, but you can learn many bad things from them too. Some projects/framework get a lot fo hype. Yet, some of their groupings of functionality, even names given to modules are misleading. They don't "reveal intention" of the programmers. They fail the "high cohesiveness" test. Books are no better. Please apply 80/20 rule in your book selection. Even a good, very complete, well-researched book like Capers Jones' 2010 "Software Engineering Best Practices" is clueless. It says 10-man Agile/XP team would take 12 years to do Windows Vista or 25 years to do an ERP package! It says there is no method till 2009 for segmentation, its term for modularization. I don't think it will help you. My point is: You must pick your model/reference/source of examples very carefully. Don't over-estimate famous names and under-estimate yourself. Here is my help, proven in my experience. It is a lot like deciding what attributes go to which DB table, what properties/methods go to which class/object etc? On a deeper level, it is a lot like arranging furniture at home, or books in a shelf. You have done such things already. Software is the same, no big deal! Worry about "cohesion" first. e.g. Books (Leo Tolstoy, James Joyce, DE Lawrence) is choesive .(HTML, CSS, John Keats. jQuery, tinymce) is not. And there are many ways to arrange things. Even taxonomists are still in serious feuds over this. Then worry about "coupling." Be "shy". "Don't talk to strangers." Don't be over-friendly. Try to make your package/DB table/class/object/module/bookshelf as self-contained, as independent as possible. Joel has talked about his admiration for the Excel team that abhor all external dependencies and that even built their own compiler.
0.067922
false
4
224
2009-07-22 22:05:47.193
Recommended ways to split some functionality into functions, modules and packages?
There comes a point where, in a relatively large sized project, one need to think about splitting the functionality into various functions, and then various modules, and then various packages. Sometimes across different source distributions (eg: extracting a common utility, such as optparser, into a separate project). The question - how does one decide the parts to put in the same module, and the parts to put in a separate module? Same question for packages.
Actually it varies for each project you create but here is an example: core package contains modules that are your project cant live without. this may contain the main functionality of your application. ui package contains modules that deals with the user interface. that is if you split the UI from your console. This is just an example. and it would really you that would be deciding which and what to go where.
0
false
4
224
2009-07-22 22:05:47.193
Recommended ways to split some functionality into functions, modules and packages?
There comes a point where, in a relatively large sized project, one need to think about splitting the functionality into various functions, and then various modules, and then various packages. Sometimes across different source distributions (eg: extracting a common utility, such as optparser, into a separate project). The question - how does one decide the parts to put in the same module, and the parts to put in a separate module? Same question for packages.
Take out a pen and piece of paper. Try to draw how your software interacts on a high level. Draw the different layers of the software etc. Group items by functionality and purpose, maybe even by what sort of technology they use. If your software has multiple abstraction layers, I would say to group them by that. On a high level, the elements of a specific layer all share the same general purpose. Now that you have your software in layers, you can divide these layers into different projects based on specific functionality or specialization. As for a certain stage that you reach in which you should do this? I'd say when you have multiple people working on the code base or if you want to keep your project as modular as possible. Hopefully your code is modular enough to do this with. If you are unable to break apart your software on a high level, then your software is probably spaghetti code and you should look at refactoring it. Hopefully that will give you something to work with.
0.265586
false
4
224
2009-07-22 22:05:47.193
Recommended ways to split some functionality into functions, modules and packages?
There comes a point where, in a relatively large sized project, one need to think about splitting the functionality into various functions, and then various modules, and then various packages. Sometimes across different source distributions (eg: extracting a common utility, such as optparser, into a separate project). The question - how does one decide the parts to put in the same module, and the parts to put in a separate module? Same question for packages.
IMHO this should probably one of the things you do earlier in the development process. I have never worked on a large-scale project, but it would make sense that you make a roadmap of what's going to be done and where. (Not trying to rib you for asking about it like you made a mistake :D ) Modules are generally grouped somehow, by purpose or functionality. You could try each implementation of an interface, or other connections.
0.067922
false
4
224
2009-07-25 17:36:18.193
How can I launch a background process in Pylons?
I am trying to write an application that will allow a user to launch a fairly long-running process (5-30 seconds). It should then allow the user to check the output of the process as it is generated. The output will only be needed for the user's current session so nothing needs to be stored long-term. I have two questions regarding how to accomplish this while taking advantage of the Pylons framework: What is the best way to launch a background process such as this with a Pylons controller? What is the best way to get the output of the background process back to the user? (Should I store the output in a database, in session data, etc.?) Edit: The problem is if I launch a command using subprocess in a controller, the controller waits for the subprocess to finish before continuing, showing the user a blank page that is just loading until the process is complete. I want to be able to redirect the user to a status page immediately after starting the subprocess, allowing it to complete on its own.
I think this has little to do with pylons. I would do it (in whatever framework) in these steps: generate some ID for the new job, and add a record in the database. create a new process, e.g. through the subprocess module, and pass the ID on the command line (*). have the process write its output to /tmp/project/ID in pylons, implement URLs of the form /job/ID or /job?id=ID. That will look into the database whether the job is completed or not, and merge the temporary output into the page. (*) It might be better for the subprocess to create another process immediately, and have the pylons process wait for the first child, so that there will be no zombie processes.
0.201295
false
1
225
2009-07-26 23:01:51.647
How to associate py extension with python launcher on Mac OS X?
Does anyone know how to associate the py extension with the python interpreter on Mac OS X 10.5.7? I have gotten as far as selecting the application with which to associate it (/System/Library/Frameworks/Python.framework/Versions/2.5/bin/python), but the python executable appears as a non-selectable grayed-out item. Any ideas?
The python.org OS X Python installers include an application called "Python Launcher.app" which does exactly what you want. It gets installed into /Applications /Python n.n/ for n.n > 2.6 or /Applications/MacPython n.n/ for 2.5 and earlier. In its preference panel, you can specify which Python executable to launch; it can be any command-line path, including the Apple-installed one at /usr/bin/python2.5. You will also need to ensure that .py is associated with "Python Launcher"; you can use the Finder's Get Info command to do that as described elsewhere. Be aware, though, that this could be a security risk if downloaded .py scripts are automatically launched by your browser(s). (Note, the Apple-supplied Python in 10.5 does not include "Python Launcher.app").
0.545705
false
3
226
2009-07-26 23:01:51.647
How to associate py extension with python launcher on Mac OS X?
Does anyone know how to associate the py extension with the python interpreter on Mac OS X 10.5.7? I have gotten as far as selecting the application with which to associate it (/System/Library/Frameworks/Python.framework/Versions/2.5/bin/python), but the python executable appears as a non-selectable grayed-out item. Any ideas?
The file associations are done with the "Get Info". You select your .PY file, select the File menu; Get Info menu item. Mid-way down the Get Info page is "Open With". You can pick the Python Launcher. There's a Change All.. button that changes the association for all .py files.
0.296905
false
3
226
2009-07-26 23:01:51.647
How to associate py extension with python launcher on Mac OS X?
Does anyone know how to associate the py extension with the python interpreter on Mac OS X 10.5.7? I have gotten as far as selecting the application with which to associate it (/System/Library/Frameworks/Python.framework/Versions/2.5/bin/python), but the python executable appears as a non-selectable grayed-out item. Any ideas?
The default python installation (atleast on 10.6.8) includes the Python Launcher.app in /System/Library/Frameworks/Python.framework/Resources/, which is aliased to the latest/current version of Python installed on the system. This application launches terminal and sets the right environment to run the script.
0
false
3
226
2009-07-27 12:44:15.817
How to exit from Python without traceback?
I would like to know how to I exit from Python without having an traceback dump on the output. I still want want to be able to return an error code but I do not want to display the traceback log. I want to be able to exit using exit(number) without trace but in case of an Exception (not an exit) I want the trace.
Use the built-in python function quit() and that's it. No need to import any library. I'm using python 3.4
0.121841
false
2
227
2009-07-27 12:44:15.817
How to exit from Python without traceback?
I would like to know how to I exit from Python without having an traceback dump on the output. I still want want to be able to return an error code but I do not want to display the traceback log. I want to be able to exit using exit(number) without trace but in case of an Exception (not an exit) I want the trace.
something like import sys; sys.exit(0) ?
0.351669
false
2
227
2009-07-27 15:11:19.977
Python POST ordered params
I have a web service that accepts passed in params using http POST but in a specific order, eg (name,password,data). I have tried to use httplib but all the Python http POST libraries seem to take a dictionary, which is an unordered data structure. Any thoughts on how to http POST params in order for Python? Thanks!
Why would you need a specific order in the POST parameters in the first place? As far as I know there are no requirements that POST parameter order is preserved by web servers. Every language I have used, has used a dictionary type object to hold these parameters as they are inherently key/value pairs.
1.2
true
1
228
2009-07-28 18:56:50.007
How to start a background process in Python?
I'm trying to port a shell script to the much more readable python version. The original shell script starts several processes (utilities, monitors, etc.) in the background with "&". How can I achieve the same effect in python? I'd like these processes not to die when the python scripts complete. I am sure it's related to the concept of a daemon somehow, but I couldn't find how to do this easily.
I haven't tried this yet but using .pyw files instead of .py files should help. pyw files dosen't have a console so in theory it should not appear and work like a background process.
0
false
1
229
2009-07-29 04:00:35.017
Convert html entities to ascii in Python
I need to convert any html entity into its ASCII equivalent using Python. My use case is that I am cleaning up some HTML used to build emails to create plaintext emails from the HTML. Right now, I only really know how to create unicode from these entities when I need ASCII (I think) so that the plaintext email reads correctly with things like accented characters. I think a basic example is the html entity "& aacute;" or á being encoded into ASCII. Furthermore, I'm not even 100% sure that ASCII is what I need for a plaintext email. As you can tell, I'm completely lost on this encoding stuff.
ASCII is the American Standard Code for Information Interchange and does not include any accented letters. Your best bet is to get Unicode (as you say you can) and encode it as UTF-8 (maybe ISO-8859-1 or some weird codepage if you're dealing with seriously badly coded user-agents/clients, sigh) -- the content type header of that part together with text/plain can express what encoding you've chosen to use (I do recommend trying UTF-8 unless you have positively demonstrated it cannot work -- it's almost universally supported these days and MUCH more flexible than any ISO-8859 or "codepage" hack!).
1.2
true
1
230
2009-07-30 03:52:42.753
Getting total/free RAM from within Python
From within a Python application, how can I get the total amount of RAM of the system and how much of it is currently free, in a cross-platform way? Ideally, the amount of free RAM should consider only physical memory that can actually be allocated to the Python process.
You can't do this with just the standard Python library, although there might be some third party package that does it. Barring that, you can use the os package to determine which operating system you're on and use that information to acquire the info you want for that system (and encapsulate that into a single cross-platform function).
0.240117
false
1
231
2009-07-30 09:22:31.380
Neural net input/output
Can anyone explain to me how to do more complex data sets like team stats, weather, dice, complex number types i understand all the math and how everything works i just dont know how to input more complex data, and then how to read the data it spits out if someone could provide examples in python that would be a big help
More complex data usually means adding more neurons in the input and output layers. You can feed each "field" of your register, properly encoded as a real value (normalized, etc.) to each input neuron, or maybe you can even decompose even further into bit fields, assigning saturated inputs of 1 or 0 to the neurons... for the output, it depends on how you train the neural network, it will try to mimic the training set outputs.
0
false
4
232
2009-07-30 09:22:31.380
Neural net input/output
Can anyone explain to me how to do more complex data sets like team stats, weather, dice, complex number types i understand all the math and how everything works i just dont know how to input more complex data, and then how to read the data it spits out if someone could provide examples in python that would be a big help
You have to add the number of units for input and output you need for the problem. If the unknown function to approximate depends on n parameter, you will have n input units. The number of output units depends on the nature of the funcion. For real functions with n real parameters you will have one output unit. Some problems, for example in forecasting of time series, you will have m output units for the m succesive values of the function. The encoding is important and depends on the choosen algorithm. For example, in backpropagation for feedforward nets, is better to transform, if possible, the greater number of features in discrete inputs, as for classification tasks. Other aspect of the encoding is that you have to evaluate the number of input and hidden units in function of the amount of data. Too many units related to data may give poor approximation due the course ff dimensionality problem. In some cases, you may to aggregate some of the input data in some way to avoid that problem or use some reduction mechanism as PCA.
0
false
4
232
2009-07-30 09:22:31.380
Neural net input/output
Can anyone explain to me how to do more complex data sets like team stats, weather, dice, complex number types i understand all the math and how everything works i just dont know how to input more complex data, and then how to read the data it spits out if someone could provide examples in python that would be a big help
You have to encode your input and your output to something that can be represented by the neural network units. ( for example 1 for "x has a certain property p" -1 for "x doesn't have the property p" if your units' range is in [-1, 1]) The way you encode your input and the way you decode your output depends on what you want to train the neural network for. Moreover, there are many "neural networks" algoritms and learning rules for different tasks( Back propagation, boltzman machines, self organizing maps).
1.2
true
4
232
2009-07-30 09:22:31.380
Neural net input/output
Can anyone explain to me how to do more complex data sets like team stats, weather, dice, complex number types i understand all the math and how everything works i just dont know how to input more complex data, and then how to read the data it spits out if someone could provide examples in python that would be a big help
Your features must be decomposed into parts that can be represented as real numbers. The magic of a Neural Net is it's a black box, the correct associations will be made (with internal weights) during the training Inputs Choose as few features as are needed to accurately describe the situation, then decompose each into a set of real valued numbers. Weather: [temp today, humidity today, temp yesterday, humidity yesterday...] the association between today's temp and today's humidity is made internally Team stats: [ave height, ave weight, max height, top score,...] Dice: not sure I understand this one, do you mean how to encode discrete values?* Complex number: [a,ai,b,bi,...] * Discrete valued features are tricky, but can still still be encoded as (0.0,1.0). The problem is they don't provide a gradient to learn the threshold on. Outputs You decide what you want the output to mean, and then encode your training examples in that format. The fewer output values, the easier to train. Weather: [tomorrow's chance of rain, tomorrow's temp,...] ** Team stats: [chance of winning, chance of winning by more than 20,...] Complex number: [x,xi,...] ** Here your training vectors would be: 1.0 if it rained the next day, 0.0 if it didn't Of course, whether or not the problem can actually be modeled by a neural net is a different question.
0.201295
false
4
232
2009-07-31 04:38:14.510
Django .."join" query?
guys, how or where is the "join" query in Django? i think that Django dont have "join"..but how ill make join? Thanks
If you're using models, the select_related method will return the object for any foreign keys you have set up (up to a limit you specify) within that model.
1.2
true
2
233
2009-07-31 04:38:14.510
Django .."join" query?
guys, how or where is the "join" query in Django? i think that Django dont have "join"..but how ill make join? Thanks
SQL Join queries are a hack because SQL doesn't have objects or navigation among objects. Objects don't need "joins". Just access the related objects.
-0.997458
false
2
233
2009-07-31 08:47:34.600
downloading files to users machine?
I am trying to download mp3 file to users machine without his/her consent while they are listening the song.So, next time they visit that web page they would not have to download same mp3, but palypack from the local file. this will save some bandwidth for me and for them. it something pandora used to do but I really don't know how to. any ideas?
Don't do this. Most files are cached anyway. But if you really want to add this (because users asked for it), make it optional (default off).
0.265586
false
2
234
2009-07-31 08:47:34.600
downloading files to users machine?
I am trying to download mp3 file to users machine without his/her consent while they are listening the song.So, next time they visit that web page they would not have to download same mp3, but palypack from the local file. this will save some bandwidth for me and for them. it something pandora used to do but I really don't know how to. any ideas?
You can't forcefully download files to a user without his consent. If that was possible you can only imagine what severe security flaw that would be. You can do one of two things: count on the browser to cache the media file serve the media via some 3rd party plugin (Flash, for example)
1.2
true
2
234
2009-07-31 15:49:14.583
how can I get the uuid module for python 2.4.3
I have an older version of python on the server i'm using and cannot upgrade it. is there a way to get the uuid module?
To continue where Alex left off.. Download the uuid-1.30.tar.gz from Alex's pypi link. unzip and untar. place the uuid.py to your application's python path (e.g., same dir with your own .py files)
0.201295
false
1
235
2009-08-02 01:22:31.573
PyOpenGL + Pygame capped to 60 FPS in Fullscreen
I'm currently working on a game engine written in pygame and I wanted to add OpenGL support. I wrote a test to see how to make pygame and OpenGL work together, and when it's running in windowed mode, it runs between 150 and 200 fps. When I run it full screen (all I did was add the FULLSCREEN flag when I set up the window), it drops down to 60 fps. I added a lot more drawing functions to see if it was just a huge performance drop, but it always ran at 60 fps. Is there something extra I need to do to tell OpenGL that it's running fullscreen or is this a limitation of OpenGL? (I am running in Windows XP)
If you are not changing your clock.tick() when you change between full screen and windowed mode this is almost certainly a vsync issue. If you are on an LCD then it's 100% certain. Unfortunately v-sync can be handled in many places including SDL, Pyopengl, your display server and your video drivers. If you are using windows you can adjust the vsync toggle in the nvidia control panel to test, and there's more than likely something in nvidia-settings for linux as well. I'd guess other manufacturers drivers have similar settings but that's a guess.
0
false
1
236
2009-08-04 04:03:09.093
How to control Webpage dialog with python
When I try to automatically download a file from some webpage using Python, I get Webpage Dialog window (I use IE). The window has two buttons, such as 'Continue' and 'Cancel'. I cannot figure out how to click on the Continue Button. The problem is that I don't know how to control Webpage Dialog with Python. I tried to use winGuiAuto to find the controls of the window, but it fails to recognize any Button type controls... An ideas? Sasha A clarification of my question: My purpose is to download stock data from a certain web site. I need to perform it for many stocks so I need python to do it for me in a repetitive way. This specific site exports the data by letting me download it in Excel file by clicking a link. However after clicking the link I get a Web Page dialog box asking me if I am sure that I want to download this file. This Web page dialog is my problem - it is not an html page and it is not a regular windows dialog box. It is something else and I cannot configure how to control it with python. It has two buttons and I need to click on one of them (i.e. Continue). It seems like it is a special kind of window implemented in IE. It is distinguished by its title which looks like this: Webpage Dialog -- Download blalblabla. If I click Continue mannually it opens a regular windows dialog box (open,save,cancel) which i know how to handle with winGuiAuto library. Tried to use this library for the Webpage Dialog window with no luck. Tried to recognize the buttons with Autoit Info tool -no luck either. In fact, maybe these are not buttons, but actually links, however I cannot see the links and there is no source code visible... What I need is someone to tell me what this Web page Dialog box is and how to control it with Python. That was my question.
You can't, and you don't want to. When you ask a question, try explaining what you are trying to achieve, and not just the task immediately before you. You are likely barking down the wrong path. There is some other way of doing what you are trying to do.
0
false
1
237
2009-08-04 18:10:52.940
With Python, can I keep a persistent dictionary and modify it?
So, I want to store a dictionary in a persistent file. Is there a way to use regular dictionary methods to add, print, or delete entries from the dictionary in that file? It seems that I would be able to use cPickle to store the dictionary and load it, but I'm not sure where to take it from there.
pickling has one disadvantage. it can be expensive if your dictionary has to be read and written frequently from disk and it's large. pickle dumps the stuff down (whole). unpickle gets the stuff up (as a whole). if you have to handle small dicts, pickle is ok. If you are going to work with something more complex, go for berkelydb. It is basically made to store key:value pairs.
0
false
3
238
2009-08-04 18:10:52.940
With Python, can I keep a persistent dictionary and modify it?
So, I want to store a dictionary in a persistent file. Is there a way to use regular dictionary methods to add, print, or delete entries from the dictionary in that file? It seems that I would be able to use cPickle to store the dictionary and load it, but I'm not sure where to take it from there.
Unpickle from file when program loads, modify as a normal dictionary in memory while program is running, pickle to file when program exits? Not sure exactly what more you're asking for here.
0.296905
false
3
238
2009-08-04 18:10:52.940
With Python, can I keep a persistent dictionary and modify it?
So, I want to store a dictionary in a persistent file. Is there a way to use regular dictionary methods to add, print, or delete entries from the dictionary in that file? It seems that I would be able to use cPickle to store the dictionary and load it, but I'm not sure where to take it from there.
Assuming the keys and values have working implementations of repr, one solution is that you save the string representation of the dictionary (repr(dict)) to file. YOu can load it using the eval function (eval(inputstring)). There are two main disadvantages of this technique: 1) Is will not work with types that have an unuseable implementation of repr (or may even seem to work, but fail). You'll need to pay at least some attention to what is going on. 2) Your file-load mechanism is basically straight-out executing Python code. Not great for security unless you fully control the input. It has 1 advantage: Absurdly easy to do.
0.050976
false
3
238
2009-08-05 19:59:22.827
In GTK, how do I make a window unable to be closed?
For example, graying out the "X" on windows systems.
Just call the set_deletable with False on the window in question. It will work as long as GTK can convince the window manager to make the window unclosable.
0.673066
false
1
239
2009-08-05 22:16:28.883
Compiling python modules with DEBUG defined on MSVC
Python rather stupidly has a pragma directive in its include files that forces a link against python26_d.lib when the DEBUG preprocessor variable is defined. This is a problem because the python installer doesn't come with python26_d.lib! So I can't build applications in MSVC in debug mode. If I temporarily #undef DEBUG for just one file I get many complaints about inconsistent DLL linkage. If I change the pragma in pythons include file I get undefined references to various debug functions. I have tried compiling my own version of python but its somehow different enough from the python that gets distributed that I can't use my modules with apps built with the vanilla version of python Can anyone give me any advice on how to get round this?
This works also when linking with static libraries. I made a copy of python26.lib, and renamed it python26_d.lib. I commented out the line #define PY_DEBUG in pyconfig.h. Also changed the pragma to "pragma comment(lib,"python26.lib")" on line 332. Voila! It worked.
0.16183
false
1
240
2009-08-09 01:02:37.763
What is the importance of an IDE when programming in Python?
I'm a beginning Python programmer, just getting my feet wet in the language and its tools and native practices. In the past, I've used languages that were tightly integrated into IDEs, and indeed I had never before considered that it was even possible to program outside of such a tool. However, much of the documentation and tutorials for Python eschew any sort of IDE, relying instead on powerful editors and interactive interpreters for writing and teaching the language. How important is an IDE to normal Python development? Are there good IDEs available for the language? If you do use an IDE for Python, how do you use it effectively?
A matter of habit and personal preferences. Me, I use vim (I have to admit emacs is at least as powerful, but my fingers are deeply trained by over 30 years of vi, and any other editor gives me the jitters, especially when it tries to imitate vi and never really manages to get it 100% right;-), occasionally an interactive environment (python itself, sometimes ipython), and on even rarer occasions a debugger (pdb). A good editor gives me all I need in term of word completion, lookup, &c. I've tried Eclipse, its plugins, eric, and Kommodo, but I just don't like them -- Wing, I think I could get used to, and I have to admit its debugger is absolutely out of this world... but, I very rarely use (or need!) advanced debugging functionality, so after every rare occasion I'd forget, and have to learn it all over again a few months later when the need arose again... nah!-)
0.265586
false
4
241
2009-08-09 01:02:37.763
What is the importance of an IDE when programming in Python?
I'm a beginning Python programmer, just getting my feet wet in the language and its tools and native practices. In the past, I've used languages that were tightly integrated into IDEs, and indeed I had never before considered that it was even possible to program outside of such a tool. However, much of the documentation and tutorials for Python eschew any sort of IDE, relying instead on powerful editors and interactive interpreters for writing and teaching the language. How important is an IDE to normal Python development? Are there good IDEs available for the language? If you do use an IDE for Python, how do you use it effectively?
How important is an IDE to normal Python development? Not very, IMHO. It's a lightweight language with much less boilerplate and simpler idioms than in some other languages, so there's less need for an IDE for that part. The standard interactive interpreter provides help and introspection functionality and a reasonable debugger (pdb). When I want a graphical look at my class hierarchies, I use epydoc to generate it. The only IDE-like functionality I sometimes wish I had is something that would help automate refactoring. Are there good IDEs available for the language? So I hear. Some of my coworkers use Wing. If you do use an IDE for Python, how do you use it effectively? N/A. I tried using Wing a few times but found that it interfered with my normal development process rather than supporting it.
0.201295
false
4
241
2009-08-09 01:02:37.763
What is the importance of an IDE when programming in Python?
I'm a beginning Python programmer, just getting my feet wet in the language and its tools and native practices. In the past, I've used languages that were tightly integrated into IDEs, and indeed I had never before considered that it was even possible to program outside of such a tool. However, much of the documentation and tutorials for Python eschew any sort of IDE, relying instead on powerful editors and interactive interpreters for writing and teaching the language. How important is an IDE to normal Python development? Are there good IDEs available for the language? If you do use an IDE for Python, how do you use it effectively?
(1) IDEs are less important than for other languages, but if you find one that is useful, it still makes things easier. Without IDEs -- what are doing? Always running Python from command line? (2-3) On my Mac there's included IDLE which I keep always open for its Python shell (it's colored unlike the one in Terminal) and I use free Komodo Edit which I consider to be well-suited for Python as it doesn't go into the language deeply but rather focuses on coloring, tab management, parsing Python output, running frequent commands etc.
0
false
4
241
2009-08-09 01:02:37.763
What is the importance of an IDE when programming in Python?
I'm a beginning Python programmer, just getting my feet wet in the language and its tools and native practices. In the past, I've used languages that were tightly integrated into IDEs, and indeed I had never before considered that it was even possible to program outside of such a tool. However, much of the documentation and tutorials for Python eschew any sort of IDE, relying instead on powerful editors and interactive interpreters for writing and teaching the language. How important is an IDE to normal Python development? Are there good IDEs available for the language? If you do use an IDE for Python, how do you use it effectively?
In contrast to the other answers i think that IDE's are very important especially for script languages. Almost all code is bad documentated and an IDE with a good debugger gives you much insides about what is really going on what datatypes are assigned to this values. Is this a hash of lists of hashes or a list of hashs of hashs. And the easy documentation lookup will save you time. But this is only important for people who need to count there time, this normally excludes beginners or hobbyists.
0.067922
false
4
241
2009-08-09 05:31:05.883
Network Support for Pygame
I am making a simple multiplayer economic game in pygame. It consists of turns of a certain length, at the end of which, data is sent to the central server. A few quick calculations are done on the data and the results are sent back to the players. My question is how I should implement the network support. I was looking at Twisted and at Pyro and any suggestions or advice would be appreciated.
I've nothing against Twisted and PyRo, but the sort of simple messages you're going to be sending don't require anything like that and might be overcomplicated by using some sort of framework. Pickling an object and sending it over a socket is actually a very easy operation and well worth trying, even if you do eventually go with a more heavyweight framework. Don't fear the network!
0.135221
false
1
242
2009-08-10 13:13:10.300
Call PHP code from Python
I'm trying to integrate an old PHP ad management system into a (Django) Python-based web application. The PHP and the Python code are both installed on the same hosts, PHP is executed by mod_php5 and Python through mod_wsgi, usually. Now I wonder what's the best way to call this PHP ad management code from within my Python code in a most efficient manner (the ad management code has to be called multiple times for each page)? The solutions I came up with so far, are the following: Write SOAP interface in PHP for the ad management code and write a SOAP client in Python which then calls the appropriate functions. The problem I see is, that will slow down the execution of the Python code considerably, since for each page served, multiple SOAP client requests are necessary in the background. Call the PHP code through os.execvp() or subprocess.Popen() using PHP command line interface. The problem here is that the PHP code makes use of the Apache environment ($_SERVER vars and other superglobals). I'm not sure if this can be simulated correctly. Rewrite the ad management code in Python. This will probably be the last resort. This ad management code just runs and runs, and there is no one remaining who wrote a piece of code for this :) I'd be quite afraid to do this ;) Any other ideas or hints how this can be done? Thanks.
I've done this in the past by serving the PHP portions directly via Apache. You could either put them in with your media files, (/site_media/php/) or if you prefer to use something more lightweight for your media server (like lighttpd), you can set up another portion of the site that goes through apache with PHP enabled. From there, you can either take the ajax route in your templates, or you can load the PHP from your views using urllib(2) or httplib(2). Better yet, wrap the urllib2 call in a templatetag, and call that in your templates.
0
false
1
243
2009-08-13 17:03:13.610
Python Twisted: restricting access by IP address
What would be the best method to restrict access to my XMLRPC server by IP address? I see the class CGIScript in web/twcgi.py has a render method that is accessing the request... but I am not sure how to gain access to this request in my server. I saw an example where someone patched twcgi.py to set environment variables and then in the server access the environment variables... but I figure there has to be a better solution. Thanks.
I'd use a firewall on windows, or iptables on linux.
0
false
1
244
2009-08-18 12:28:03.767
Proxies in Python FTP application
I'm developing an FTP client in Python ftplib. How do I add proxies support to it (most FTP apps I have seen seem to have it)? I'm especially thinking about SOCKS proxies, but also other types... FTP, HTTP (is it even possible to use HTTP proxies with FTP program?) Any ideas how to do it?
Standard module ftplib doesn't support proxies. It seems the only solution is to write your own customized version of the ftplib.
0.135221
false
1
245
2009-08-19 06:07:17.173
Is there an easy way to use a python tempfile in a shelve (and make sure it cleans itself up)?
Basically, I want an infinite size (more accurately, hard-drive rather than memory bound) dict in a python program I'm writing. It seems like the tempfile and shelve modules are naturally suited for this, however, I can't see how to use them together in a safe manner. I want the tempfile to be deleted when the shelve is GCed (or at guarantee deletion after the shelve is out of use, regardless of when), but the only solution I can come up with for this involves using tempfile.TemporaryFile() to open a file handle, getting the filename from the handle, using this filename for opening a shelve, keeping the reference to the file handle to prevent it from getting GCed (and the file deleted), and then putting a wrapper on the shelve that stores this reference. Anyone have a better solution than this convoluted mess? Restrictions: Can only use the standard python library and must be fully cross platform.
I would rather inherit from shelve.Shelf, and override the close method (*) to unlink the files. Notice that, depending on the specific dbm module being used, you may have more than one file that contains the shelf. One solution could be to create a temporary directory, rather than a temporary file, and remove anything in the directory when done. The other solution would be to bind to a specific dbm module (say, bsddb, or dumbdbm), and remove specifically those files that these libraries create. (*) notice that the close method of a shelf is also called when the shelf is garbage collected. The only case how you could end up with garbage files is when the interpreter crashes or gets killed.
1.2
true
1
246
2009-08-20 07:59:36.877
how to install new packages with python 3.1.1?
I've tried to install pip on windows, but it's not working: giving me ImportError: No module named pkg_resources easy_install doesn't have version 3.1 or so, just 2.5, and should be replaced by pim. is there easy way to install it on windows?
setuptools doesn't quite work on Python 3.1 yet. Try installing packages with regular distutils, or use binary packages (.exe, .msi) provided by the package author.
1.2
true
1
247
2009-08-20 10:13:54.017
Django - Edit data in db
I have a question regarding editing/saving data in database using Django. I have template that show data from database. And after each record i have link that link you to edit page. But now is the question how to edit data in db without using admin panel? I run thought tutorial in djangobook but i didn't see how to achieve this without using the shell Thanks in advice!
You can use Django authenticaion system to create users and giving them permissions to modify the data.
0
false
1
248
2009-08-20 16:21:38.407
How do I programmatically pull lists/arrays of (itunes urls to) apps in the iphone app store?
I'd like to know how to pragmatically pull lists of apps from the iphone app store. I'd code this in python (via the google app engine) or in an iphone app. My goal would be to select maybe 5 of them and present them to the user. (for instance a top 5 kind of thing, or advanced filtering or queries)
Unfortunately the only API that seems to be around for Apple's app store is a commercial offering from ABTO; nobody seems to have developed a free one. I'm afraid you'll have to resort to "screen scraping" -- urlget things, use beautifulsoup or the like for interpreting the HTML you get, and be ready to fix breakages whenever Apple tweaks their formats &c. It seems Apple has no interest in making such a thing available to developers (although as far as I can't tell they're not actively fighting against it either, they appear to just not care).
1.2
true
1
249
2009-08-23 23:42:52.663
How to submit data of a flash form? [python]
I would like to know if it is possible to submit a flash form from python and, if it is, how? I have done form submitting from python before, but the forms were HTML not flash. I really have no idea on how to do this. In my research about this I kept getting 'Ming'. However, Ming is only to create .swf files and that's not what I intend to do. Any help on this is greatly appreciated.
You can set the url attribute (I think it's url, please correct me if I'm wrong) on a Flash form control to a Python script - then it will pass it through HTTP POST like any normal HTML form. You've got nothing to be afraid of, it uses the same protocol to communicate, it's just a different submission process.
1.2
true
2
250
2009-08-23 23:42:52.663
How to submit data of a flash form? [python]
I would like to know if it is possible to submit a flash form from python and, if it is, how? I have done form submitting from python before, but the forms were HTML not flash. I really have no idea on how to do this. In my research about this I kept getting 'Ming'. However, Ming is only to create .swf files and that's not what I intend to do. Any help on this is greatly appreciated.
For your flash app, there's no difference if the backend is python, php or anything, so you can follow a normal "php + flash contact form" guide and then build the backend using django or any other python web framework, receive the information from the http request (GET or POST, probably the last one) and do whatever you wanted to do with them. Notice the response from python to flash works the same as with php, it's just http content, so you can use XML or even better, JSON.
0
false
2
250
2009-08-25 00:30:51.707
Importing a text file into SQL Server in Python
I am writing a python script that will be doing some processing on text files. As part of that process, i need to import each line of the tab-separated file into a local MS SQL Server (2008) table. I am using pyodbc and I know how to do this. However, I have a question about the best way to execute it. I will be looping through the file, creating a cursor.execute(myInsertSQL) for each line of the file. Does anyone see any problems waiting to commit the statements until all records have been looped (i.e. doing the commit() after the loop and not inside the loop after each individual execute)? The reason I ask is that some files will have upwards of 5000 lines. I didn't know if trying to "save them up" and committing all 5000 at once would cause problems. I am fairly new to python, so I don't know all of these issues yet. Thanks.
If I understand what you are doing, Python is not going to be a problem. Executing a statement inside a transaction does not create cumulative state in Python. It will do so only at the database server itself. When you commit you will need to make sure the commit occurred, since having a large batch commit may conflict with intervening changes in the database. If the commit fails, you will have to re-run the batch again. That's the only problem that I am aware of with large batches and Python/ODBC (and it's not even really a Python problem, since you would have that problem regardless.) Now, if you were creating all the SQL in memory, and then looping through the memory-representation, that might make more sense. Still, 5000 lines of text on a modern machine is really not that big of a deal. If you start needing to process two orders of magnitude more, you might need to rethink your process.
1.2
true
1
251
2009-08-30 16:17:03.933
How to implement a multiprocessing priority queue in Python?
Anybody familiar with how I can implement a multiprocessing priority queue in python?
Depending on your requirements you could use the operating system and the file system in a number of ways. How large will the queue grow and how fast does it have to be? If the queue may be big but you are willing to open a couple files for every queue access you could use a BTree implementation to store the queue and file locking to enforce exclusive access. Slowish but robust. If the queue will remain relatively small and you need it to be fast you might be able to use shared memory on some operating systems... If the queue will be small (1000s of entries) and you don't need it to be really fast you could use something as simple as a directory with files containing the data with file locking. This would be my preference if small and slow is okay. If the queue can be large and you want it to be fast on average, then you probably should use a dedicated server process like Alex suggests. This is a pain in the neck however. What are your performance and size requirements?
0
false
2
252
2009-08-30 16:17:03.933
How to implement a multiprocessing priority queue in Python?
Anybody familiar with how I can implement a multiprocessing priority queue in python?
I had the same use case. But with a finite number of priorities. What I am ending up doing is creating one Queue per priority, and my Process workers will try to get the items from those queues, starting with the most important queue to the less important one (moving from one queue to the other is done when the queue is empty)
0.067922
false
2
252
2009-09-02 00:03:32.233
How to deal with user authentication and wrongful modification in scripting languages?
I'm building a centralized desktop application using Python/wxPython. One of the requirements is User authentication, which I'm trying to implement using LDAP (although this is not mandatory). Users of the system will be mechanical and electrical engineers making budgets, and the biggest problem would be industrial espionage. Its a common problem that leaks occur commonly from the bottom on informal ways, and this could pose problems. The system is set up in such a way that every user has access to all and only the information it needs, so that no one person but the people on top has monetary information on the whole project. The problem is that, for every way I can think to implement the authentication system, Python's openness makes me think of at least one way of bypassing/getting sensible information from the system, because "compiling" with py2exe is the closest I can get to obfuscation of the code on Windows. I'm not really trying to hide the code, but rather make the authentication routine secure by itself, make it in such a way that access to the code doesn't mean capability to access the application. One thing I wanted to add, was some sort of code signing to the access routine, so the user can be sure that he is not running a modified client app. One of the ways I've thought to avoid this is making a C module for the authentication, but I would rather not have to do that. Of course this question is changing now and is not just "Could anyone point me in the right direction as to how to build a secure authentication system running on Python? Does something like this already exist?", but "How do you harden an scripting (Python) against wrongful modification?"
Possibly: The user enters their credentials into the desktop client. The client says to the server: "Hi, my name username and my password is password". The server checks these. The server says to the client: "Hi, username. Here is your secret token: ..." Subsequently the client uses the secret token together with the username to "sign" communications with the server.
0.201295
false
2
253
2009-09-02 00:03:32.233
How to deal with user authentication and wrongful modification in scripting languages?
I'm building a centralized desktop application using Python/wxPython. One of the requirements is User authentication, which I'm trying to implement using LDAP (although this is not mandatory). Users of the system will be mechanical and electrical engineers making budgets, and the biggest problem would be industrial espionage. Its a common problem that leaks occur commonly from the bottom on informal ways, and this could pose problems. The system is set up in such a way that every user has access to all and only the information it needs, so that no one person but the people on top has monetary information on the whole project. The problem is that, for every way I can think to implement the authentication system, Python's openness makes me think of at least one way of bypassing/getting sensible information from the system, because "compiling" with py2exe is the closest I can get to obfuscation of the code on Windows. I'm not really trying to hide the code, but rather make the authentication routine secure by itself, make it in such a way that access to the code doesn't mean capability to access the application. One thing I wanted to add, was some sort of code signing to the access routine, so the user can be sure that he is not running a modified client app. One of the ways I've thought to avoid this is making a C module for the authentication, but I would rather not have to do that. Of course this question is changing now and is not just "Could anyone point me in the right direction as to how to build a secure authentication system running on Python? Does something like this already exist?", but "How do you harden an scripting (Python) against wrongful modification?"
How malicious are your users? Really. Exactly how malicious? If your users are evil sociopaths and can't be trusted with a desktop solution, then don't build a desktop solution. Build a web site. If your users are ordinary users, they'll screw the environment up by installing viruses, malware and keyloggers from porn sites before they try to (a) learn Python (b) learn how your security works and (c) make a sincere effort at breaking it. If you actually have desktop security issues (i.e., public safety, military, etc.) then rethink using the desktop. Otherwise, relax, do the right thing, and don't worry about "scripting". C++ programs are easier to hack because people are lazy and permit SQL injection.
1.2
true
2
253
2009-09-02 00:07:14.003
On localhost, how do I pick a free port number?
I'm trying to play with inter-process communication and since I could not figure out how to use named pipes under Windows I thought I'll use network sockets. Everything happens locally. The server is able to launch slaves in a separate process and listens on some port. The slaves do their work and submit the result to the master. How do I figure out which port is available? I assume I cannot listen on port 80 or 21? I'm using Python, if that cuts the choices down.
You can listen on whatever port you want; generally, user applications should listen to ports 1024 and above (through 65535). The main thing if you have a variable number of listeners is to allocate a range to your app - say 20000-21000, and CATCH EXCEPTIONS. That is how you will know if a port is unusable (used by another process, in other words) on your computer. However, in your case, you shouldn't have a problem using a single hard-coded port for your listener, as long as you print an error message if the bind fails. Note also that most of your sockets (for the slaves) do not need to be explicitly bound to specific port numbers - only sockets that wait for incoming connections (like your master here) will need to be made a listener and bound to a port. If a port is not specified for a socket before it is used, the OS will assign a useable port to the socket. When the master wants to respond to a slave that sends it data, the address of the sender is accessible when the listener receives data. I presume you will be using UDP for this?
0.3154
false
2
254
2009-09-02 00:07:14.003
On localhost, how do I pick a free port number?
I'm trying to play with inter-process communication and since I could not figure out how to use named pipes under Windows I thought I'll use network sockets. Everything happens locally. The server is able to launch slaves in a separate process and listens on some port. The slaves do their work and submit the result to the master. How do I figure out which port is available? I assume I cannot listen on port 80 or 21? I'm using Python, if that cuts the choices down.
Bind the socket to port 0. A random free port from 1024 to 65535 will be selected. You may retrieve the selected port with getsockname() right after bind().
1
false
2
254
2009-09-03 07:50:17.240
Importing external module in IronPython
I'm currently working on an application written in C#, which I'm embedding IronPython in. I generally have no problems about it, but there's one thing that I don't know how to deal with. I want to import an external module into the script. How can I do that? Simple import ext_lib doesn't work. Should I add a path to the lib to sys.path? Maybe it is possible to copy the lib's .py file into app directory and import from there? EDIT: I finally chosen another solution - compiled my script with py2exe and I'm just running it from main C# app with Process (without using IronPython). Anyway, thanks for help ;)
If you have installed IronPython from NuGet packages and you want modules from the CPython Standard Library then the best way to do it is by installing the IronPython.StdLib NuGet package which is from the same authors of IronPython.
0.386912
false
1
255
2009-09-04 01:40:30.637
calculate user inputed time with Python
I need to calculate (using python) how much time a user has inputed, whether they input something like 3:30 or 3.5. I'm not really sure what the best way to go about this is and I thought I'd ask for advice from the experts. === Edit ================== To specify more clearly, I want the user to input hours and minutes or just minutes. I want them to be able to input the time in two formats, either in hh:mm (3:30 or 03:30) or as a float (3.5) hours. The overall goal is to keep track of the time they have worked. So, I will be adding the time they enter up to get a total.
First of all, you'll need some conventions. Is 3.55 five minutes to four hours, five milliseconds to four seconds, or 3 and 55/100 of a minute/hour/second? The same applies to 3:55. At least have a distinction between dot and colon, specifying that a dot means a fraction and a colon, a separator of hour/minute/second. Although you haven't specified what "time" is (since or o'clock?), you'll need that too. Then, it's simple a matter of having a final representation of a time that you want to work with, and keep converting the input until your final representation is achieved. Let's say you decide that ultimately time should be represented as MM:SS (two digits for minutes, a colon, two digits for seconds), you'll need to search the string for allowed occurrences of characters, and act accordingly. For example, having a colon and a dot at the same time is not allowed. If there's a single colon, you have a fraction, therefore you'll treat the second part as a fraction of 60. Keep doing this until you have your final representation, and then just do what you gotta do with said "time". I don't know on what constraints you're working with, but the problem could be narrowed if instead of a single "time" input, you had two: The first, where people type the hours, and the second, where they type the minutes. Of course, that would only work if you can divide the input...
0
false
3
256
2009-09-04 01:40:30.637
calculate user inputed time with Python
I need to calculate (using python) how much time a user has inputed, whether they input something like 3:30 or 3.5. I'm not really sure what the best way to go about this is and I thought I'd ask for advice from the experts. === Edit ================== To specify more clearly, I want the user to input hours and minutes or just minutes. I want them to be able to input the time in two formats, either in hh:mm (3:30 or 03:30) or as a float (3.5) hours. The overall goal is to keep track of the time they have worked. So, I will be adding the time they enter up to get a total.
There are a few possible solutions, but at some point you're gonna run into ambiguous cases that will result in arbitrary conversions. Overall I'd suggest taking any input and parsing the separators (whether : or . or something else) and then converting to seconds based on some schema of units you've defined. Alternatively you could do a series of try/except statements to test it against different time formatting schemes to see if it matches. I'm not sure what will be best in your case...
0
false
3
256
2009-09-04 01:40:30.637
calculate user inputed time with Python
I need to calculate (using python) how much time a user has inputed, whether they input something like 3:30 or 3.5. I'm not really sure what the best way to go about this is and I thought I'd ask for advice from the experts. === Edit ================== To specify more clearly, I want the user to input hours and minutes or just minutes. I want them to be able to input the time in two formats, either in hh:mm (3:30 or 03:30) or as a float (3.5) hours. The overall goal is to keep track of the time they have worked. So, I will be adding the time they enter up to get a total.
Can you do this with a GUI and restrict the user input? Processing the text seems super error prone otherwise (on the part of the user, not to mention the programmer), and for hours worked... you sort-of want to get that right.
0
false
3
256
2009-09-05 12:33:03.783
Can I use __init__.py to define global variables?
I want to define a constant that should be available in all of the submodules of a package. I've thought that the best place would be in in the __init__.py file of the root package. But I don't know how to do this. Suppose I have a few subpackages and each with several modules. How can I access that variable from these modules? Of course, if this is totally wrong, and there is a better alternative, I'd like to know it.
You can define global variables from anywhere, but it is a really bad idea. import the __builtin__ module and modify or add attributes to this modules, and suddenly you have new builtin constants or functions. In fact, when my application installs gettext, I get the _() function in all my modules, without importing anything. So this is possible, but of course only for Application-type projects, not for reusable packages or modules. And I guess no one would recommend this practice anyway. What's wrong with a namespace? Said application has the version module, so that I have "global" variables available like version.VERSION, version.PACKAGE_NAME etc.
0.201295
false
1
257
2009-09-07 06:56:51.613
C++ with Python embedding: crash if Python not installed
I'm developing on Windows, and I've searched everywhere without finding anyone talking about this kind of thing. I made a C++ app on my desktop that embedded Python 3.1 using MSVC. I linked python31.lib and included python31.dll in the app's run folder alongside the executable. It works great. My extension and embedding code definitely works and there are no crashes. I sent the run folder to my friend who doesn't have Python installed, and the app crashes for him during the scripting setup phase. A few hours ago, I tried the app on my laptop that has Python 2.6 installed. I got the same crash behavior as my friend, and through debugging found that it was the Py_Initialize() call that fails. I installed Python 3.1 on my laptop without changing the app code. I ran it and it runs perfectly. I uninstalled Python 3.1 and the app crashes again. I put in code in my app to dynamically link from the local python31.dll, to ensure that it was using it, but I still get the crash. I don't know if the interpreter needs more than the DLL to start up or what. I haven't been able to find any resources on this. The Python documentation and other guides do not seem to ever address how to distribute your C/C++ applications that use Python embedding without having the users install Python locally. I know it's more of an issue on Windows than on Unix, but I've seen a number of Windows C/C++ applications that embed Python locally and I'm not sure how they do it. What else do I need other than the DLL? Why does it work when I install Python and then stop working when I uninstall it? It sounds like it should be so trivial; maybe that's why nobody really talks about it. Nevertheless, I can't really explain how to deal with this crash issue. Thank you very much in advance.
A zip of the Python standard library worked for me with Python27. I zipped the contents of Lib and dll, and made sure there was no additional python27-subfolder or Lib or dll subfolder. i.e. just a zip named python27.zip containing all the files. I copied that zip and the python27.dll alongside the executable.
0.545705
false
2
258
2009-09-07 06:56:51.613
C++ with Python embedding: crash if Python not installed
I'm developing on Windows, and I've searched everywhere without finding anyone talking about this kind of thing. I made a C++ app on my desktop that embedded Python 3.1 using MSVC. I linked python31.lib and included python31.dll in the app's run folder alongside the executable. It works great. My extension and embedding code definitely works and there are no crashes. I sent the run folder to my friend who doesn't have Python installed, and the app crashes for him during the scripting setup phase. A few hours ago, I tried the app on my laptop that has Python 2.6 installed. I got the same crash behavior as my friend, and through debugging found that it was the Py_Initialize() call that fails. I installed Python 3.1 on my laptop without changing the app code. I ran it and it runs perfectly. I uninstalled Python 3.1 and the app crashes again. I put in code in my app to dynamically link from the local python31.dll, to ensure that it was using it, but I still get the crash. I don't know if the interpreter needs more than the DLL to start up or what. I haven't been able to find any resources on this. The Python documentation and other guides do not seem to ever address how to distribute your C/C++ applications that use Python embedding without having the users install Python locally. I know it's more of an issue on Windows than on Unix, but I've seen a number of Windows C/C++ applications that embed Python locally and I'm not sure how they do it. What else do I need other than the DLL? Why does it work when I install Python and then stop working when I uninstall it? It sounds like it should be so trivial; maybe that's why nobody really talks about it. Nevertheless, I can't really explain how to deal with this crash issue. Thank you very much in advance.
In addition to pythonxy.dll, you also need the entire Python library, i.e. the contents of the lib folder, plus the extension modules, i.e. the contents of the DLLs folder. Without the standard library, Python won't even start, since it tries to find os.py (in 3.x; string.py in 2.x). On startup, it imports a number of modules, in particular site.py. There are various locations where it searches for the standard library; in your cases, it eventually finds it in the registry. Before, uses the executable name (as set through Py_SetProgramName) trying to find the landmark; it also checks for a file python31.zip which should be a zipped copy of the standard library. It also checks for a environment variable PYTHONHOME. You are free to strip the library from stuff that you don't need; there are various tools that compute dependencies statically (modulefinder in particular). If you want to minimize the number of files, you can link all extension modules statically into your pythonxy.dll, or even link pythonxy.dll statically into your application use the freeze tool; this will allow linking the byte code of the standard library into your pythonxy.dll. (alternatively to 2.) use pythonxy.zip for the standard library.
1.2
true
2
258
2009-09-07 07:08:12.007
Django: Simple rate limiting
Many of my views fetch external resources. I want to make sure that under heavy load I don't blow up the remote sites (and/or get banned). I only have 1 crawler so having a central lock will work fine. So the details: I want to allow at most 3 queries to a host per second, and have the rest block for a maximum of 15 seconds. How could I do this (easily)? Some thoughts : Use django cache Seems to only have 1 second resolution Use a file based semaphore Easy to do locks for concurrency. Not sure how to make sure only 3 fetches happen a second. Use some shared memory state I'd rather not install more things, but will if I have to.
What about using a different process to handle scraping, and a queue for the communication between it and Django? This way you would be able to easily change the number of concurrent requests, and it would also automatically keep track of the requests, without blocking the caller. Most of all, I think it would help lowering the complexity of the main application (in Django).
0.201295
false
1
259
2009-09-07 09:36:41.473
Upgrade python in linux
I have a linux VPS that uses an older version of python (2.4.3). This version doesn't include the UUID module, but I need it for a project. My options are to upgrade to python2.6 or find a way to make uuid work with the older version. I am a complete linux newbie. I don't know how to upgrade python safely or how I could get the UUID modules working with the already installed version. What is a better option and how would I go about doing it?
The safest way to upgrading Python is to install it to a different location (away from the default system path). To do this, download the source of python and do a ./configure --prefix=/opt (Assuming you want to install it to /opt which is where most install non system dependant stuff to) The reason why I say this is because some other system libraries may depend on the current version of python. Another reason is that as you are doing your own custom development, it is much better to have control over what version of the libraries (or interpreters) you are using rather than have a operating system patch break something that was working before. A controlled upgrade is better than having the application break on you all of a sudden.
0.673066
false
2
260
2009-09-07 09:36:41.473
Upgrade python in linux
I have a linux VPS that uses an older version of python (2.4.3). This version doesn't include the UUID module, but I need it for a project. My options are to upgrade to python2.6 or find a way to make uuid work with the older version. I am a complete linux newbie. I don't know how to upgrade python safely or how I could get the UUID modules working with the already installed version. What is a better option and how would I go about doing it?
The best solution will be installing python2.6 in the choosen directory - It will you give you access to many great features and better memory handling (infamous python=2.4 memory leak problem). I have got several pythons installed onto my two computers, I found that the best solution for are two directories: $HOME/usr-32 $HOME/usr-64 respectively to using operating system (I share $HOME between 32 and 64 bit versions of Linux). In each I have one directory for every application/program, for example: ls ~/usr-64/python-2.6.2/ bin include lib share It leads completetely to avoiding conflicts between version and gives great portability (you can use usb pendrives etc). Python 2.6.2 in previously example has been installed with option: ./configure --prefix=$HOME/usr-64/python-2.6.2
0
false
2
260
2009-09-10 23:48:56.300
send an arbitrary number of inputs from python to a .exe
p = subprocess.Popen(args = "myprog.exe" + " " + str(input1) + " " + str(input2) + " " + str(input3) + " " + strpoints, stdout = subprocess.PIPE) in the code above, input1, input2, and input3 are all integers that get converted to strings. the variable "strpoints" is a list of arbitrary length of strings. input1 tells myprog the length of strpoints. of course, when i try to run the above code, i get the following error message: TypeError: Can't convert 'list' object to str implicitly how do i pass all the elements of strpoints to myprog.exe? am i doomed to having to do str(strpoints) and then have myprog.exe parse this for commas, apostrophes, etc.? e.g., `>>> x = ['a', 'b'] `>>> str(x) "['a', 'b']" or should i create a huge string in advance? e.g., '>>> x = ['a', 'b'] '>>> stringify(x) ' a b' where stringify would be something like def stringify(strlist): rlist = "" for i in strlist: rlist = rlist + i + " " return rlist
Avoid concatenating all arguments into one string using that string. It's a lot simpler and better and safer to just pass a sequence (list or tuple) of arguments. This is specially true if any argument contains a space character (which is quite common for filenames).
0.101688
false
1
261
2009-09-12 20:10:43.223
Python - Virtualenv , python 3?
Seems everyone recommends virtualenv for multiple python versions (on osx), but does it even work with python 3.0? I downloaded it, and it doesn't seem to.. And I don't really understand how it works, Can you 'turn on' on env at a time or something? What I want is to leave the system python 2.5 (obviously), and to have python 3.1.1 with subversion pygame to write my own stuff, and python 2.6 with normal stable pygame to use to run other things, like pygame games downloaded from pygame.org. Any help on how to accomplish that? Thanks. OK I realized virtualenv is not what I'm looking for.
Your use case doesn't actually need virtualenv. You just need to install several different Python versions.
1.2
true
2
262
2009-09-12 20:10:43.223
Python - Virtualenv , python 3?
Seems everyone recommends virtualenv for multiple python versions (on osx), but does it even work with python 3.0? I downloaded it, and it doesn't seem to.. And I don't really understand how it works, Can you 'turn on' on env at a time or something? What I want is to leave the system python 2.5 (obviously), and to have python 3.1.1 with subversion pygame to write my own stuff, and python 2.6 with normal stable pygame to use to run other things, like pygame games downloaded from pygame.org. Any help on how to accomplish that? Thanks. OK I realized virtualenv is not what I'm looking for.
Not sure if I understood you correctly, but here goes :) I don't know about OS X, but in Linux you can install both 2.6 and 3. Then you can either specify to use python25 or python3, or change the /usr/bin/python symlink to the version you want to use by default.
0
false
2
262
2009-09-14 23:28:28.893
Default save path for Python IDLE?
Does anyone know where or how to set the default path/directory on saving python scripts prior to running? On a Mac it wants to save them in the top level ~/Documents directory. I would like to specify a real location. Any ideas?
On Windows (Vista at least, which is what I'm looking at here), shortcut icons on the desktop have a "Start in" field where you can set the directory used as the current working directory when the program starts. Changing that works for me. Anything like that on the Mac? (Starting in the desired directory from the command line works, too.)
0.037089
false
8
263
2009-09-14 23:28:28.893
Default save path for Python IDLE?
Does anyone know where or how to set the default path/directory on saving python scripts prior to running? On a Mac it wants to save them in the top level ~/Documents directory. I would like to specify a real location. Any ideas?
I actually just discovered the easiest answer, if you use the shortcut link labeled "IDLE (Python GUI)". This is in Windows Vista, so I don't know if it'll work in other OS's. 1) Right-click "Properties". 2) Select "Shortcut" tab. 3) In "Start In", write file path (e.g. "C:\Users..."). Let me know if this works!
0.147343
false
8
263
2009-09-14 23:28:28.893
Default save path for Python IDLE?
Does anyone know where or how to set the default path/directory on saving python scripts prior to running? On a Mac it wants to save them in the top level ~/Documents directory. I would like to specify a real location. Any ideas?
For OS X: Open a new finder window,then head over to applications. Locate your Python application. (For my mac,it's Python 3.5) Double click on it. Right click on the IDLE icon,show package contents. Then go into the contents folder,then resources. Now,this is the important part: (Note: You must be the administrator or have the administrator's password for the below to work) Right click on the idlemain.py,Get Info. Scroll all the way down. Make sure under the Sharing & Permissions tab,your "name"(Me) is on it with the privilege as Read & Write. If not click on the lock symbol and unlock it. Then add/edit yourself to have the Read & Write privilege. Lastly,as per Ned Deily's instructions,edit the line: os.chdir(os.path.expanduser('~/Documents')) with your desired path and then save the changes. Upon restarting the Python IDLE,you should find that your default Save as path to be the path you've indicated.
0.037089
false
8
263
2009-09-14 23:28:28.893
Default save path for Python IDLE?
Does anyone know where or how to set the default path/directory on saving python scripts prior to running? On a Mac it wants to save them in the top level ~/Documents directory. I would like to specify a real location. Any ideas?
I am using windows 7 and by going to Start-> IDLE(Python 3.6 32-bit) The click on properties and then in the shortcut tab go to Start in and entering the desired path worked for me kindly note if IDLE is open and running while you do this you'll have to shut it down and restart it for this to work
0.037089
false
8
263
2009-09-14 23:28:28.893
Default save path for Python IDLE?
Does anyone know where or how to set the default path/directory on saving python scripts prior to running? On a Mac it wants to save them in the top level ~/Documents directory. I would like to specify a real location. Any ideas?
It seems like you can get idle into the directory you want if you run any module from that directory. I had previously tried opening idlemain.py through the path browser. I was able to open and edit the file, but it seemed like I wasn't able to save my modifications. I'm just glad to hear other people are having this problem. I just thought I was being stupid.
0.074076
false
8
263
2009-09-14 23:28:28.893
Default save path for Python IDLE?
Does anyone know where or how to set the default path/directory on saving python scripts prior to running? On a Mac it wants to save them in the top level ~/Documents directory. I would like to specify a real location. Any ideas?
If you open a module, that sets the default working directory. Start IDLE. File -> Open to open your file. And set the current working directory.
0.037089
false
8
263
2009-09-14 23:28:28.893
Default save path for Python IDLE?
Does anyone know where or how to set the default path/directory on saving python scripts prior to running? On a Mac it wants to save them in the top level ~/Documents directory. I would like to specify a real location. Any ideas?
If you locate the idlelib directory in your Python install, it will have a few files with the .def extension. config-main.def has instructions on where to put the custom config files. However, looking through these I did not find any configurable paths (your install may vary). Looks like you might need to crack open the editor code to alter it.
0
false
8
263
2009-09-14 23:28:28.893
Default save path for Python IDLE?
Does anyone know where or how to set the default path/directory on saving python scripts prior to running? On a Mac it wants to save them in the top level ~/Documents directory. I would like to specify a real location. Any ideas?
In Windows 10+, click the Windows Start button, then type idle, and then right-click on the IDLE desktop app and open the file location. This should bring you to the Start Menu shortcuts for Python, and you'll find a shortcut to IDLE there. Right-click on the IDLE shortcut and select properties. Set the "Start in" directory to be where you want default save path to be.
0.074076
false
8
263
2009-09-15 04:48:36.987
Symmetrically adressable matrix
I'm looking to create a 2d matrix of integers with symmetric addressing ( i.e. matrix[2,3] and matrix[3,2] will return the same value ) in python. The integers will have addition and subtraction done on them, and be used for logical comparisons. My initial idea was to create the integer objects up front and try to fill a list of lists with some python equivalent of pointers. I'm not sure how to do it, though. What is the best way to implement this, and should I be using lists or another data structure?
You're probably better off using a full square numpy matrix. Yes, it wastes half the memory storing redundant values, but rolling your own symmetric matrix in Python will waste even more memory and CPU by storing and processing the integers as Python objects.
0.201295
false
2
264
2009-09-15 04:48:36.987
Symmetrically adressable matrix
I'm looking to create a 2d matrix of integers with symmetric addressing ( i.e. matrix[2,3] and matrix[3,2] will return the same value ) in python. The integers will have addition and subtraction done on them, and be used for logical comparisons. My initial idea was to create the integer objects up front and try to fill a list of lists with some python equivalent of pointers. I'm not sure how to do it, though. What is the best way to implement this, and should I be using lists or another data structure?
You only need to store the lower triangle of the matrix. Typically this is done with one n(n+1)/2 length list. You'll need to overload the __getitem__ method to interpret what the entry means.
0.101688
false
2
264
2009-09-17 19:44:09.870
Finding the command for a specific PID in Linux from Python
I'd like to know if it's possible to find out the "command" that a PID is set to. When I say command, I mean what you see in the last column when you run the command "top" in a linux shell. I'd like to get this information from Python somehow when I have a specific PID. Any help would be great. Thanks.
Look in /proc/$PID/cmdline, and then os.readlink() on /proc/$PID/exe. /proc/$PID/cmdline is not necessarily going to be correct, as a program can change its argument vector or it may not contain a full path. Three examples of this from my current process list are: avahi-daemon: chroot helper qmgr -l -t fifo -u /usr/sbin/postgrey --pidfile=/var/run/postgrey.pid --daemonize --inet=127.0.0.1:60000 --delay=55 That first one is obvious - it's not a valid path or program name. The second is just an executable with no path name. The third looks ok, but that whole command line is actually in argv[0], with spaces separating the arguments. Normally you should have NUL separated arguments. All this goes to show that /proc/$PID/cmdline (or the ps(1) output) is not reliable. However, nor is /proc/$PID/exe. Usually it is a symlink to the executable that is the main text segment of the process. But sometimes it has " (deleted)" after it if the executable is no longer in the filesystem. Also, the program that is the text segment is not always what you want. For instance, /proc/$PID/exe from that /usr/sbin/postgrey example above is /usr/bin/perl. This will be the case for all interpretted scripts (#!). I settled on parsing /proc/$PID/cmdline - taking the first element of the vector, and then looking for spaces in that, and taking all before the first space. If that was an executable file - I stopped there. Otherwise I did a readlink(2) on /proc/$PID/exe and removed any " (deleted)" strings on the end. That first part will fail if the executable filename actually has spaces in it. There's not much you can do about that. BTW. The argument to use ps(1) instead of /proc/$PID/cmdline does not apply in this case, since you are going to fall back to /proc/$PID/exe. You will be dependent on the /proc filesystem, so you may as well read it with read(2) instead of pipe(2), fork(2), execve(2), readdir(3)..., write(2), read(2). While ps and /proc/$PID/cmdline may be the same from the point of view of lines of python code, there's a whole lot more going on behind the scenes with ps.
0.283556
false
3
265
2009-09-17 19:44:09.870
Finding the command for a specific PID in Linux from Python
I'd like to know if it's possible to find out the "command" that a PID is set to. When I say command, I mean what you see in the last column when you run the command "top" in a linux shell. I'd like to get this information from Python somehow when I have a specific PID. Any help would be great. Thanks.
Look in /proc/$PID/cmdline
0.336246
false
3
265
2009-09-17 19:44:09.870
Finding the command for a specific PID in Linux from Python
I'd like to know if it's possible to find out the "command" that a PID is set to. When I say command, I mean what you see in the last column when you run the command "top" in a linux shell. I'd like to get this information from Python somehow when I have a specific PID. Any help would be great. Thanks.
The proc filesystem exports this (and other) information. Look at the /proc/PID/cmd symlink.
0
false
3
265
2009-09-18 17:52:53.017
Passing Python Data to JavaScript via Django
I'm using Django and Apache to serve webpages. My JavaScript code currently includes a data object with values to be displayed in various HTML widgets based on the user's selection from a menu of choices. I want to derive these data from a Python dictionary. I think I know how to embed the JavaScript code in the HTML, but how do I embed the data object in that script (on the fly) so the script's functions can use it? Put another way, I want to create a JavaScript object or array from a Python dictionary, then insert that object into the JavaScript code, and then insert that JavaScript code into the HTML. I suppose this structure (e.g., data embedded in variables in the JavaScript code) is suboptimal, but as a newbie I don't know the alternatives. I've seen write-ups of Django serialization functions, but these don't help me until I can get the data into my JavaScript code in the first place. I'm not (yet) using a JavaScript library like jQuery.
Putting Java Script embedded into Django template is rather always bad idea. Rather, because there are some exceptions from this rule. Everything depends on the your Java Script code site and functionality. It is better to have seperately static files, like JS, but the problem is that every seperate file needs another connect/GET/request/response mechanism. Sometimes for small one, two liners code os JS to put this into template, bun then use django templatetags mechanism - you can use is in other templates ;) About objects - the same. If your site has AJAX construction/web2.0 like favour - you can achieve very good effect putting some count/math operation onto client side. If objects are small - embedded into template, if large - response them in another connection to avoid hangind page for user.
0.050976
false
3
266
2009-09-18 17:52:53.017
Passing Python Data to JavaScript via Django
I'm using Django and Apache to serve webpages. My JavaScript code currently includes a data object with values to be displayed in various HTML widgets based on the user's selection from a menu of choices. I want to derive these data from a Python dictionary. I think I know how to embed the JavaScript code in the HTML, but how do I embed the data object in that script (on the fly) so the script's functions can use it? Put another way, I want to create a JavaScript object or array from a Python dictionary, then insert that object into the JavaScript code, and then insert that JavaScript code into the HTML. I suppose this structure (e.g., data embedded in variables in the JavaScript code) is suboptimal, but as a newbie I don't know the alternatives. I've seen write-ups of Django serialization functions, but these don't help me until I can get the data into my JavaScript code in the first place. I'm not (yet) using a JavaScript library like jQuery.
You can include <script> tags inside your .html templates, and then build your data structures however is convenient for you. The template language isn't only for HTML, it can also do Javascript object literals. And Paul is right: it might be best to use a json module to create a JSON string, then insert that string into the template. That will handle the quoting issues best, and deal with deep structures with ease.
0.151877
false
3
266
2009-09-18 17:52:53.017
Passing Python Data to JavaScript via Django
I'm using Django and Apache to serve webpages. My JavaScript code currently includes a data object with values to be displayed in various HTML widgets based on the user's selection from a menu of choices. I want to derive these data from a Python dictionary. I think I know how to embed the JavaScript code in the HTML, but how do I embed the data object in that script (on the fly) so the script's functions can use it? Put another way, I want to create a JavaScript object or array from a Python dictionary, then insert that object into the JavaScript code, and then insert that JavaScript code into the HTML. I suppose this structure (e.g., data embedded in variables in the JavaScript code) is suboptimal, but as a newbie I don't know the alternatives. I've seen write-ups of Django serialization functions, but these don't help me until I can get the data into my JavaScript code in the first place. I'm not (yet) using a JavaScript library like jQuery.
It is suboptimal. Have you considered passing your data as JSON using django's built in serializer for that?
0.101688
false
3
266
2009-09-20 16:01:16.207
How to stream binary data in python
I want to stream a binary data using python. I do not have any idea how to achieve it. I did created python socket program using SOCK_DGRAM. Problem with SOCK_STREAM is that it does not work over internet as our isp dont allow tcp server socket. I want to transmit screen shots periodically to remote computer. I have an idea of maintaining a Que of binary data and have two threads write and read synchronously. I do not want to use VNC . How do I do it? I did written server socket and client socket using SOCK_STREAM it was working on localhost and did not work over internet even if respective ip's are placed. We also did tried running tomcat web server on one pc and tried accessing via other pc on internet and was not working.
There are two problems here. First problem, you will need to be able to address the remote party. This is related to what you referred to as "does not work over Internet as most ISP don't allow TCP server socket". It is usually difficult because the other party could be placed behind a NAT or a firewall. As for the second problem, the problem of actual transmitting of data after you can make a TCP connection, python socket would work if you can address the remote party.
1.2
true
2
267
2009-09-20 16:01:16.207
How to stream binary data in python
I want to stream a binary data using python. I do not have any idea how to achieve it. I did created python socket program using SOCK_DGRAM. Problem with SOCK_STREAM is that it does not work over internet as our isp dont allow tcp server socket. I want to transmit screen shots periodically to remote computer. I have an idea of maintaining a Que of binary data and have two threads write and read synchronously. I do not want to use VNC . How do I do it? I did written server socket and client socket using SOCK_STREAM it was working on localhost and did not work over internet even if respective ip's are placed. We also did tried running tomcat web server on one pc and tried accessing via other pc on internet and was not working.
SOCK_STREAM is the correct way to stream data. What you're saying about ISPs makes very little sense; they don't control whether or not your machine listens on a certain port on an interface. Perhaps you're talking about firewall/addressing issues? If you insist on using UDP (and you shouldn't because you'll have to worry about packets arriving out of place or not arriving at all) then you'll need to first use socket.bind and then socket.recvfrom in a loop to read data and keep track of open connections. It'll be hard work to do correctly.
0.545705
false
2
267
2009-09-21 17:09:59.850
How to build sqlite for Python 2.4?
I would like to use pysqlite interface between Python and sdlite database. I have already Python and SQLite on my computer. But I have troubles with installation of pysqlite. During the installation I get the following error message: error: command 'gcc' failed with exit status 1 As far as I understood the problems appears because version of my Python is 2.4.3 and SQLite is integrated in Python since 2.5. However, I also found out that it IS possible to build sqlite for Python 2.4 (using some tricks, probably). Does anybody know how to build sqlite for Python 2.4? As another option I could try to install higher version of Python. However I do not have root privileges. Does anybody know what will be the easiest way to solve the problem (build SQLite fro Python 2.4, or install newer version of Python)? I have to mention that I would not like to overwrite the old version version of Python. Thank you in advance.
If you don't have root privileges, I would recommend installing a more recent version of Python in your home directory and then adding your local version to your PATH. It seems easier to go that direction than to try to make sqlite work with an old version of Python. You will also be doing yourself a favor by using a recent version of Python, because you'll have access to the numerous recent improvements in the language.
0
false
2
268
2009-09-21 17:09:59.850
How to build sqlite for Python 2.4?
I would like to use pysqlite interface between Python and sdlite database. I have already Python and SQLite on my computer. But I have troubles with installation of pysqlite. During the installation I get the following error message: error: command 'gcc' failed with exit status 1 As far as I understood the problems appears because version of my Python is 2.4.3 and SQLite is integrated in Python since 2.5. However, I also found out that it IS possible to build sqlite for Python 2.4 (using some tricks, probably). Does anybody know how to build sqlite for Python 2.4? As another option I could try to install higher version of Python. However I do not have root privileges. Does anybody know what will be the easiest way to solve the problem (build SQLite fro Python 2.4, or install newer version of Python)? I have to mention that I would not like to overwrite the old version version of Python. Thank you in advance.
I had the same trouble with gcc failing with Ubuntu Karmic. I fixed this by installing the python-dev package. In my case, I'm working with python2.4, so I installed the python2.4-dev package. The python-dev package should work for python2.6.
0
false
2
268
2009-09-22 07:53:03.900
How to create a MAPI32.dll stub to be able to "send as attachment" from MS Word?
Microsoft Word has "send as attachment" functionality which creates a new message in Outlook with the document attached. I would like to replace Outlook with a custom mail agent, but I do not know how to achieve this. Now my mail agent is simply a program that runs, and takes a file name as parameter. As far as I know, "send as attachment" is using some DLL/API called MAPI. I would need to change my app so that it does not simply accept file name arguments, but can receive MAPI(?) calls MS Word uses when "sending as attachment". Further, I need to change the default mail agent by creating my own MAPI32.dll stub which simply redirects to my app. I'd appreciate if anyone had more info on how this could be achieved!
OK, to answer my own question. I need to build a DLL with "MAPISendDocuments" and/or "MAPISendMail" functions defined. This DLL can have any name, and is referenced in the registry at HKLM/Software/Clients/Mail/MyMailApp/DLLPath. Found examples using Delphi...
0
false
1
269
2009-09-22 20:57:06.170
What are sqlite development headers and how to install them?
I am trying to install pysqlite and have troubles with that. I found out that the most probable reason of that is missing sqlite headers and I have to install them. However, I have no ideas what these headers are (where I can find them, what they are doing and how to install them). Can anybody, pleas, help me with that?
For me this worked (Redhat/CentOS): $ sudo yum install sqlite-devel
0.740859
false
2
270
2009-09-22 20:57:06.170
What are sqlite development headers and how to install them?
I am trying to install pysqlite and have troubles with that. I found out that the most probable reason of that is missing sqlite headers and I have to install them. However, I have no ideas what these headers are (where I can find them, what they are doing and how to install them). Can anybody, pleas, help me with that?
pysqlite needs to compiled/build before you can use it. This requires C language header files (*.H) which come with the source code of sqllite itself. i.e. sqllite and pysqlite are two different things. Did you install sqlite prior to trying and build pysqllte ? (or maybe you did, but did you do so just with the binaries; you need the source package (or at least its headers) for pysqlite purposes.
0
false
2
270
2009-09-23 09:53:04.933
Install python 2.6 in CentOS
I have a shell that runs CentOS. For a project I'm doing, I need python 2.5+, but centOS is pretty dependent on 2.4. From what I've read, a number of things will break if you upgrade to 2.5. I want to install 2.5 separately from 2.4, but I'm not sure how to do it. So far I've downloaded the source tarball, untarred it, and did a ./configure --prefix=/opt which is where I want it to end up. Can I now just make, make install ? Or is there more?
No, that's it. You might want to make sure you have all optional library headers installed too so you don't have to recompile it later. They are listed in the documentation I think. Also, you can install it even in the standard path if you do make altinstall. That way it won't override your current default "python".
0.591696
false
1
271
2009-09-25 19:02:55.960
Python: undo write to file
What is the best way to undo the writing to a file? If I'm going through a loop and writing one line at a time, and I want to undo the previous write and replace it with something else, how do I go about doing that? Any ideas? Thanks in advance!
Try to write to your files lazily: Don't write until you are finally certain you need to do it.
0.3154
false
1
272
2009-09-29 00:09:27.583
ElementTree in Python 2.6.2 Processing Instructions support?
I'm trying to create XML using the ElementTree object structure in python. It all works very well except when it comes to processing instructions. I can create a PI easily using the factory function ProcessingInstruction(), but it doesn't get added into the elementtree. I can add it manually, but I can't figure out how to add it above the root element where PI's are normally placed. Anyone know how to do this? I know of plenty of alternative methods of doing it, but it seems that this must be built in somewhere that I just can't find.
Yeah, I don't believe it's possible, sorry. ElementTree provides a simpler interface to (non-namespaced) element-centric XML processing than DOM, but the price for that is that it doesn't support the whole XML infoset. There is no apparent way to represent the content that lives outside the root element (comments, PIs, the doctype and the XML declaration), and these are also discarded at parse time. (Aside: this appears to include any default attributes specified in the DTD internal subset, which makes ElementTree strictly-speaking a non-compliant XML processor.) You can probably work around it by subclassing or monkey-patching the Python native ElementTree implementation's write() method to call _write on your extra PIs before _writeing the _root, but it could be a bit fragile. If you need support for the full XML infoset, probably best stick with DOM.
0.16183
false
1
273