prefix
stringclasses
1 value
input_text
stringlengths
19
27.3k
target_text
stringlengths
2
24.8k
QA
send file using post from python script is there way to send file using post from python script
yes you would use the urllib module and encode using the multipart form data content type here is some sample code to get you started it is bit more than just file uploading but you should be able to read through it and see how it works user agent image uploader default message image current of total import logging import os from os path import abspath isabs isdir isfile join import random import string import sys import mimetypes import urllib import httplib import time import re def random string length return join random choice string letters for ii in range length def encode multipart data data files boundary random string def get content type filename return mimetypes guess type filename or application octet stream def encode field field name return boundary content disposition form data name field name str data field name def encode file field name filename files field name return boundary content disposition form data name filename field name filename content type get content type filename open filename rb read lines for name in data lines extend encode field name for name in files lines extend encode file name lines extend boundary body join lines headers content type multipart form data boundary boundary content length str len body return body headers def send post url data files req urllib request url connection httplib httpconnection req get host connection request post req get selector encode multipart data data files response connection getresponse logging debug response response read logging debug code response status response reason def make upload file server thread delay message none username none email none password none delay max int delay or def upload file path current total assert isabs path assert isfile path logging debug uploading to path server message template string template message or default message data max file size sub mode regist com message template safe substitute current current total total resto thread name username or email email or pwd password or random string files upfile path send post server data files logging info uploaded path rand delay random randint delay delay logging debug sleeping for seconds rand delay time sleep rand delay return upload file def upload directory path upload file assert isabs path assert isdir path matching filenames file matcher re compile jpe gif png re ignorecase for dirpath dirnames filenames in os walk path for name in filenames file path join dirpath name logging debug testing file path file path if file matcher search file path matching filenames append file path else logging info ignoring non image file path total count len matching filenames for index file path in enumerate matching filenames upload file file path index total count def run upload options paths upload file make upload file options for arg in paths path abspath arg if isdir path upload directory path upload file elif isfile path upload file path else logging error no such path path logging info done
QA
send file using post from python script is there way to send file using post from python script
this code might be of use to you
QA
change command method for tkinter button in python create new button object but did not specify the command option upon creation is there way in tkinter to change the command onclick function after the object has been created
though eli courtwright program will work fine what you really seem to want though is just way to reconfigure after instantiation any attribute which you could have set when you instantiated how you do so is by way of the configure method from tkinter import tk button def goodbye world print goodbye world nwait changed my mind button configure text hello world command hello world def hello world print hello world nwait changed my mind button configure text goodbye world command goodbye world root tk button button root text hello world command hello world button pack root mainloop fine if you use only the mouse if you care about tabbing and using space or enter on buttons then you will have to implement duplicating existing code keypress events too setting the command option through configure is much easier the only attribute that cannot change after instantiation is name
QA
how to copy file to remote server in python using scp or ssh have text file on my local machine that is generated by daily python script run in cron would like to add bit of code to have that file sent securely to my server over ssh
there are couple of different ways to approach the problem wrap command line programs use python library that provides ssh capabilities eg paramiko or twisted conch each approach has its own quirks you will need to setup ssh keys to enable password less logins if you are wrapping system commands like ssh scp or rsync you can embed password in script using paramiko or some other library but you might find the lack of documentation frustrating especially if you are not familiar with the basics of the ssh connection eg key exchanges agents etc it probably goes without saying that ssh keys are almost always better idea than passwords for this sort of stuff note its hard to beat rsync if you plan on transferring files via ssh especially if the alternative is plain old scp have used paramiko with an eye towards replacing system calls but found myself drawn back to the wrapped commands due to their ease of use and immediate familiarity you might be different gave conch the once over some time ago but it did not appeal to me if opting for the system call path python offers an array of options such as os system or the commands subprocess modules would go with the subprocess module if using version
QA
how to import module given the full path how can load python module given its full path note that the file can be anywhere in the filesystem as it is configuration option
def import file full path to module try import os module dir module file os path split full path to module module name module ext os path splitext module file save cwd os getcwd os chdir module dir module obj import module name module obj file full path to module globals module name module obj os chdir save cwd except raise importerror import file home somebody somemodule py
QA
are tuples more efficient than lists in python is there any performance difference between tuples and lists when it comes to instantiation and retrieval of elements
tuples should be slightly more efficient and because of that faster than lists because they are immutable
QA
static class variables in python is it possible to have static class variables or methods in python what syntax is required to do this
variables declared inside the class definition but not inside method are class or static variables class myclass myclass as millerdev points out this creates class level variable but this is distinct from any instance level variable so you could have myclass myclass this is different from and java but not so different from where static member cannot be accessed using reference to an instance see what the python tutorial has to say on the subject of classes and class objects steve johnson has already answered regarding static methods also documented under built in functions in the python library reference class staticmethod def arg arg beidy recommends classmethods over staticmethod as the method then receives the class type as the first argument but am still little fuzzy on the advantages of this approach over staticmethod if you are too then it probably does not matter
QA
is there way around coding in python without the tab indent whitespace criteria want to start using python for small projects but the fact that misplaced tab or indent can throw compile error is really getting on my nerves is there some type of setting to turn this off am currently using notepad is there maybe an ide that would take care of the tabs and indenting
from future import braces
QA
are tuples more efficient than lists in python is there any performance difference between tuples and lists when it comes to instantiation and retrieval of elements
in general you might expect tuples to be slightly faster however you should definitely test your specific case if the difference might impact the performance of your program remember premature optimization is the root of all evil python makes this very easy timeit is your friend python timeit loops best of usec per loop python timeit loops best of usec per loop and python timeit loops best of usec per loop python timeit loops best of usec per loop so in this case instantiation is almost an order of magnitude faster for the tuple but item access is actually somewhat faster for the list so if you are creating few tuples and accessing them many many times it may actually be faster to use lists instead of course if you want to change an item the list will definitely be faster since you would need to create an entire new tuple to change one item of it since tuples are immutable
QA
static class variables in python is it possible to have static class variables or methods in python what syntax is required to do this
personally would use classmethod whenever needed static method mainly because get the class as an argument class myobj object def mymethod cls mymethod classmethod mymethod or use decorator class myobj object classmethod def mymethod cls for static properties its time you look up some python definition variable can always change there are two types of them mutable and immutable also there are class attributes and instance attributes nothing really like static attributes in the sense of java why use static method in pythonic sense if it has no relation whatever to the class if were you would either use classmethod or define the method independent from the class
QA
static class variables in python is it possible to have static class variables or methods in python what syntax is required to do this
static methods in python are called classmethods take look at the following code class myclass def myinstancemethod self print output from an instance method classmethod def mystaticmethod cls print output from static method myclass myinstancemethod traceback most recent call last file stdin line in module typeerror unbound method myinstancemethod must be called myclass mystaticmethod output from static method notice that when we call the method myinstancemethod we get an error this is because it requires that method be called on an instance of this class the method mystaticmethod is set as classmethod using the decorator classmethod just for kicks and giggles we could call myinstancemethod on the class by passing in an instance of the class like so myclass myinstancemethod myclass output from an instance method
QA
best way to open socket in python want to open tcp client socket in python do have to go through all the low level bsd create socket handle connect socket stuff or is there simpler one line way
opening sockets in python is pretty simple you really just need something like this import socket sock socket socket sock connect address port and then you can send and recv like any other socket
QA
are tuples more efficient than lists in python is there any performance difference between tuples and lists when it comes to instantiation and retrieval of elements
the dis module disassembles the byte code for function and is useful to see the difference between tuples and lists in this case you can see that accessing an element generates identical code but that assigning tuple is much faster than assigning list def def import dis dis dis load const load const load const load const load const build list store fast load fast load const binary subscr store fast load const none return value dis dis load const store fast load fast load const binary subscr store fast load const none return value
QA
best way to open socket in python want to open tcp client socket in python do have to go through all the low level bsd create socket handle connect socket stuff or is there simpler one line way
for developing portable network programs of any sort in python twisted is quite useful one of its benefits is providing convenient layer above low level socket apis
QA
best way to open socket in python want to open tcp client socket in python do have to go through all the low level bsd create socket handle connect socket stuff or is there simpler one line way
ok this code worked socket socket connect ip port send my request print recv close it was quite difficult to work that out from the python socket module documentation so will accept the anti answer
QA
is there way around coding in python without the tab indent whitespace criteria want to start using python for small projects but the fact that misplaced tab or indent can throw compile error is really getting on my nerves is there some type of setting to turn this off am currently using notepad is there maybe an ide that would take care of the tabs and indenting
check the options of your editor or find an editor ide that allows you to convert tabs to spaces usually set the options of my editor to substitute the tab character with spaces and never run into any problems
QA
static class variables in python is it possible to have static class variables or methods in python what syntax is required to do this
blair conrad said static variables declared inside the class definition but not inside method are class or static variables class test object test there are few gotcha here carrying on from the example above test static variable accessed via instance but if we assign to the instance test we have not changed the static variable we have overwritten test on by creating new attribute test to change the static variable we do it by assigning to the class test you test you changes to do not affect new instances of test namespaces are one honking great idea let us do more of those test dict dict you dict notice how the instance variable got out of sync with the static class variable when the attribute was set directly on this is because was re bound within the namespace which is distinct from the test namespace if you want to change the value of static variable you must change it within the scope or object where it was originally defined put static in quotes because python does not really have static variables in the sense that and java do although it does not say anything specific about static variables or methods the python tutorial has some relevant information on classes and class objects steve johnson also answered regarding static methods also documented under built in functions in the python library reference class test object staticmethod def arg arg beid also mentioned classmethod which is similar to staticmethod classmethod first argument is the class object example class test object class or static variable classmethod def cls arg here we can use cls instead of the class name test if arg cls cls arg would the the same as test arg
QA
libxml on os needs sudo when trying to use libxml as myself get an error saying the package cannot be found if run as as super user am able to import fine have installed python and all libxml and libxml py related libraries via fink and own the entire path including the library any ideas why would still need to sudo
check your path run echo path
QA
how to copy file to remote server in python using scp or ssh have text file on my local machine that is generated by daily python script run in cron would like to add bit of code to have that file sent securely to my server over ssh
to do this in python not wrapping scp through subprocess popen or similar with the paramiko library you would do something like this import os import paramiko ssh paramiko sshclient ssh load host keys os path expanduser os path join ssh known hosts ssh connect server username username password password sftp ssh open sftp sftp put localpath remotepath sftp close ssh close you would probably want to deal with unknown hosts errors creating any directories necessary and so on
QA
automate firefox with python been scouring the net for something like firewatir but for python am trying to automate firefox on linux any suggestions
the pyxpcom extension is one possibility but looking at what firewatir provides have to nd the suggestion for twill it is based on mechanize which might also be useful in this context
QA
can implement web user authentication system in python without post my university does not support the post cgi method know it is crazy and was hoping to be able to have system where user can have username and password and log in securely is this even possible if it is not how would you do it with post just out of curiosity cheers
you could use http authentication if supported you would have to add ssl as all methods post get and http auth well except digest hhtp authentication send plaintext get is basically just like post it just has limit on the amount of data you can send which is usually lot smaller than post and semantic difference which makes get not good candidate from that point of view even if technically they both can do it as for examples what are you using there are many choices in python like the cgi module or some framework like django cherrypy and so on
QA
can implement web user authentication system in python without post my university does not support the post cgi method know it is crazy and was hoping to be able to have system where user can have username and password and log in securely is this even possible if it is not how would you do it with post just out of curiosity cheers
you can actually do it all with get methods however you will want to use full challenge response protocol for the logins you can hash on the client side using javascript you just need to send out unique challenge each time you will also want to use ssl to ensure that no one can see the strings as they go across in some senses there is no real security difference between get and post requests as they both go across in plaintext in other senses and in practice get is are hell of lot easier to intercept and is all over most people logs and your web browser history or as suggested by the other posters use different method entirely like http auth digest auth or some higher level authentication scheme like ad ldap kerberos or shib however kind of assumed that if you did not have post you would not have these either
QA
can implement web user authentication system in python without post my university does not support the post cgi method know it is crazy and was hoping to be able to have system where user can have username and password and log in securely is this even possible if it is not how would you do it with post just out of curiosity cheers
with bit of javascript you could have the client hash the entered password and server generated nonce and use that in an http get
QA
take screenshot via python script linux want to take screenshot via python script and unobtrusively save it am only interested in the linux solution and should support any based environment
short search turned up gtkshots looks like it might help you as it is gpled python screenshot program so should have what you need in it
QA
can implement web user authentication system in python without post my university does not support the post cgi method know it is crazy and was hoping to be able to have system where user can have username and password and log in securely is this even possible if it is not how would you do it with post just out of curiosity cheers
good choice http digest authentication harder to pull off well but an option client side hashing with javascript
QA
take screenshot via python script linux want to take screenshot via python script and unobtrusively save it am only interested in the linux solution and should support any based environment
import imagegrab img imagegrab grab img save test jpg jpeg this requires python imaging library
QA
project structure for google app engine started an application in google app engine right when it came out to play with the technology and work on pet project that had been thinking about for long time but never gotten around to starting the result is bowlsk however as it has grown and features have been added it has gotten really difficult to keep things organized mainly due to the fact that this is my first python project and did not know anything about it until started working what have main level contains all py files did not know how to make packages work all html templates for main level pages subdirectories separate folders for css images js etc folders that hold html templates for subdirecty type urls example http www bowlsk com maps to homepage default package template at index html http www bowlsk com games view series html series maps to viewseriespage again default package template at games view series html it is nasty how do restructure had ideas main folder containing appdef indexes main py subfolder for code does this have to be my first package subfolder for templates folder heirarchy would match package heirarchy individual subfolders for css images js etc main folder containing appdef indexes main py subfolder for code templates this way have the handler class right next to the template because in this stage am adding lots of features so modifications to one mean modifications to the other again do have to have this folder name be the first package name for my classes would like the folder to be src but do not want my classes to be src whateverpage is there best practice with django on the horizon is there something can do now to improve my ability to integrate with it when it becomes the official gae templating engine would simply start trying these things and seeing which seems better but pydev refactoring support does not seem to handle package moves very well so it will likely be non trivial task to get all of this working again
first would suggest you have look at rapid development with python django and google app engine gvr describes general standard project layout on page of his slide presentation here will post slightly modified version of the layout structure from that page pretty much follow this pattern myself you also mentioned you had trouble with packages just make sure each of your sub folders has an init py file it is ok if its empty boilerplate files these hardly vary between projects app yaml direct all non static requests to main py main py initialize app and send it all requests project lay out static static files served directly by app engine myapp py app specific python code views py models py tests py init py and more templates html templates or myapp templates html here are some code examples that may help as well main py import wsgiref handlers from google appengine ext import webapp from myapp views import application webapp wsgiapplication indexhandler foo foohandler debug true def main wsgiref handlers cgihandler run application myapp views py import os import datetime import logging import time from google appengine api import urlfetch from google appengine ext webapp import template from google appengine api import users from google appengine ext import webapp from models import class indexhandler webapp requesthandler def get self date foo do some processing template values data data path os path join os path dirname file templates main html self response out write template render path template values class foohandler webapp requesthandler def get self logging debug start of handler myapp models py from google appengine ext import db class samplemodel db model think this layout works great for new and relatively small to medium projects for larger projects would suggest breaking up the views and models to have their own sub folders with something like project lay out static static files served directly by app engine js js images gif png jpg css css myapp app structure models py views py tests py templates html templates
QA
why are python private methods not actually private python gives us the ability to create private methods and variables within class by prepending double underscores to the name like this myprivatemethod how then can one explain this class myclass def mypublicmethod self print public method def myprivatemethod self print this is private obj myclass obj mypublicmethod public method obj myprivatemethod traceback most recent call last file line in attributeerror myclass instance has no attribute myprivatemethod dir obj myclass myprivatemethod doc module mypublicmethod obj myclass myprivatemethod this is private what is the deal will explain this little for those who did not quite get that class myclass def mypublicmethod self print public method def myprivatemethod self print this is private obj myclass what did there is create class with public method and private method and instantiate it next call its public method obj mypublicmethod public method next try and call its private method obj myprivatemethod traceback most recent call last file line in attributeerror myclass instance has no attribute myprivatemethod everything looks good here we are unable to call it it is in fact private well actually it is not running dir on the object reveals new magical method that python creates magically for all of your private methods dir obj myclass myprivatemethod doc module mypublicmethod this new method name is always an underscore followed by the class name followed by the method name obj myclass myprivatemethod this is private so much for encapsulation eh in any case would always heard python does not support encapsulation so why even try what gives
from http www faqs org docs diveintopython fileinfo private html strictly speaking private methods are accessible outside their class just not easily accessible nothing in python is truly private internally the names of private methods and attributes are mangled and unmangled on the fly to make them seem inaccessible by their given names you can access the parse method of the mp fileinfo class by the name mp fileinfo parse acknowledge that this is interesting then promise to never ever do it in real code private methods are private for reason but like many other things in python their privateness is ultimately matter of convention not force
QA
why are python private methods not actually private python gives us the ability to create private methods and variables within class by prepending double underscores to the name like this myprivatemethod how then can one explain this class myclass def mypublicmethod self print public method def myprivatemethod self print this is private obj myclass obj mypublicmethod public method obj myprivatemethod traceback most recent call last file line in attributeerror myclass instance has no attribute myprivatemethod dir obj myclass myprivatemethod doc module mypublicmethod obj myclass myprivatemethod this is private what is the deal will explain this little for those who did not quite get that class myclass def mypublicmethod self print public method def myprivatemethod self print this is private obj myclass what did there is create class with public method and private method and instantiate it next call its public method obj mypublicmethod public method next try and call its private method obj myprivatemethod traceback most recent call last file line in attributeerror myclass instance has no attribute myprivatemethod everything looks good here we are unable to call it it is in fact private well actually it is not running dir on the object reveals new magical method that python creates magically for all of your private methods dir obj myclass myprivatemethod doc module mypublicmethod this new method name is always an underscore followed by the class name followed by the method name obj myclass myprivatemethod this is private so much for encapsulation eh in any case would always heard python does not support encapsulation so why even try what gives
it is not like you absolutly cannot get around privateness of members in any language pointer arithmetics in reflections in net java the point is that you get an error if you try to call the private method by accident but if you want to shoot yourself in the foot go ahead and do it edit you do not try to secure your stuff by oo encapsulation do you
QA
why are python private methods not actually private python gives us the ability to create private methods and variables within class by prepending double underscores to the name like this myprivatemethod how then can one explain this class myclass def mypublicmethod self print public method def myprivatemethod self print this is private obj myclass obj mypublicmethod public method obj myprivatemethod traceback most recent call last file line in attributeerror myclass instance has no attribute myprivatemethod dir obj myclass myprivatemethod doc module mypublicmethod obj myclass myprivatemethod this is private what is the deal will explain this little for those who did not quite get that class myclass def mypublicmethod self print public method def myprivatemethod self print this is private obj myclass what did there is create class with public method and private method and instantiate it next call its public method obj mypublicmethod public method next try and call its private method obj myprivatemethod traceback most recent call last file line in attributeerror myclass instance has no attribute myprivatemethod everything looks good here we are unable to call it it is in fact private well actually it is not running dir on the object reveals new magical method that python creates magically for all of your private methods dir obj myclass myprivatemethod doc module mypublicmethod this new method name is always an underscore followed by the class name followed by the method name obj myclass myprivatemethod this is private so much for encapsulation eh in any case would always heard python does not support encapsulation so why even try what gives
the class stuff naming convention let us the programmer know he is not meant to access stuff from outside the name mangling makes it unlikely anyone will do it by accident true you still can work around this it is even easier than in other languages which by the way also let you do this but no python programmer would do this if he cares about encapsulation
QA
why are python private methods not actually private python gives us the ability to create private methods and variables within class by prepending double underscores to the name like this myprivatemethod how then can one explain this class myclass def mypublicmethod self print public method def myprivatemethod self print this is private obj myclass obj mypublicmethod public method obj myprivatemethod traceback most recent call last file line in attributeerror myclass instance has no attribute myprivatemethod dir obj myclass myprivatemethod doc module mypublicmethod obj myclass myprivatemethod this is private what is the deal will explain this little for those who did not quite get that class myclass def mypublicmethod self print public method def myprivatemethod self print this is private obj myclass what did there is create class with public method and private method and instantiate it next call its public method obj mypublicmethod public method next try and call its private method obj myprivatemethod traceback most recent call last file line in attributeerror myclass instance has no attribute myprivatemethod everything looks good here we are unable to call it it is in fact private well actually it is not running dir on the object reveals new magical method that python creates magically for all of your private methods dir obj myclass myprivatemethod doc module mypublicmethod this new method name is always an underscore followed by the class name followed by the method name obj myclass myprivatemethod this is private so much for encapsulation eh in any case would always heard python does not support encapsulation so why even try what gives
its just one of those language design choices on some level they are justified they make it so you need to go pretty far out of your way to try and call the method and if you really need it that badly you must have pretty good reason debugging hooks and testing come to mind as possible applications used responsibly of course
QA
python authentication api am looking for python library that will help me to create an authentication method for desktop app am writing have found several method in web framework such as django or turbogears just want kind of username password association stored into local file can write it by myself but am really it already exists and will be better solution am not very fluent with encryption
think you should make your own authentication method as you can make it fit your application best but use library for encryption such as pycrypto or some other more lightweight library by the way if you need windows binaries for pycrypto you can get them here
QA
why are python private methods not actually private python gives us the ability to create private methods and variables within class by prepending double underscores to the name like this myprivatemethod how then can one explain this class myclass def mypublicmethod self print public method def myprivatemethod self print this is private obj myclass obj mypublicmethod public method obj myprivatemethod traceback most recent call last file line in attributeerror myclass instance has no attribute myprivatemethod dir obj myclass myprivatemethod doc module mypublicmethod obj myclass myprivatemethod this is private what is the deal will explain this little for those who did not quite get that class myclass def mypublicmethod self print public method def myprivatemethod self print this is private obj myclass what did there is create class with public method and private method and instantiate it next call its public method obj mypublicmethod public method next try and call its private method obj myprivatemethod traceback most recent call last file line in attributeerror myclass instance has no attribute myprivatemethod everything looks good here we are unable to call it it is in fact private well actually it is not running dir on the object reveals new magical method that python creates magically for all of your private methods dir obj myclass myprivatemethod doc module mypublicmethod this new method name is always an underscore followed by the class name followed by the method name obj myclass myprivatemethod this is private so much for encapsulation eh in any case would always heard python does not support encapsulation so why even try what gives
the phrase commonly used is we are all consenting adults here by prepending single underscore do not expose or double underscore hide you are telling the user of your class that you intend the member to be private in some way however you are trusting everyone else to behave responsibly and respect that unless they have compelling reason not to debuggers code completion if you truly must have something that is private then you can implement it in an extension in for cpython in most cases however you simply learn the pythonic way of doing things
QA
how should unit test code generator this is difficult and open ended question know but thought would throw it to the floor and see if anyone had any interesting suggestions have developed code generator that takes our python interface to our code generated via swig and generates code needed to expose this as webservices when developed this code did it using tdd but have found my tests to be brittle as hell because each test essentially wanted to verify that for given bit of input code which happens to be header would get given bit of outputted code wrote small engine that reads test definitions from xml input files and generates test cases from these expectations the problem is dread going in to modify the code at all that and the fact that the unit tests themselves are complex and brittle so am trying to think of alternative approaches to this problem and it strikes me am perhaps tackling it the wrong way maybe need to focus more on the outcome ie does the code generate actually run and do what want it to rather than does the code look the way want it to has anyone got any experiences of something similar to this they would care to share
just wanted to point out that you can still achieve fine grained testing while verifying the results you can test individual chunks of code by nesting them inside some setup and verification code int generated code assert provided you have your generated code assembled from smaller chunks and the chunks do not change frequently you can exercise more conditions and test little better and hopefully avoid having all your tests break when you change specifics of one chunk
QA
open source alternative to matlab fmincon function is there an open source alternative to matlab fmincon function for constrained linear optimization am rewriting matlab program to use python numpy scipy and this is the only function have not found an equivalent to numpy based solution would be ideal but any language will do
the open source python package scipy has quite large set of optimization routines including some for multivariable problems with constraints which is what fmincon does believe once you have scipy installed type the following at the python command prompt help scipy optimize the resulting document is extensive and includes the following which believe might be of use to you constrained optimizers multivariate fmin bfgs zhu byrd and nocedal bfgs constrained optimizer if you use this please quote their papers see help fmin tnc truncated newton code originally written by stephen nash and adapted to by jean sebastien roy fmin cobyla constrained optimization by linear approximation
QA
python user input and commandline arguments how do have python script that can accept user input assuming this is possible and how do make it read in arguments if run from the command line
var raw input please enter something print you entered var
QA
python user input and commandline arguments how do have python script that can accept user input assuming this is possible and how do make it read in arguments if run from the command line
the best way to process command line arguments is the argparse module use raw input to get user input if you import the readline module your users will have line editing and history
QA
python authentication api am looking for python library that will help me to create an authentication method for desktop app am writing have found several method in web framework such as django or turbogears just want kind of username password association stored into local file can write it by myself but am really it already exists and will be better solution am not very fluent with encryption
if you want simple then use dictionary where the keys are the usernames and the values are the passwords encrypted with something like sha pickle it to from disk as this is desktop application am assuming the overhead of keeping it in memory will be negligible for example import pickle import hashlib load from disk pwd file mypasswords if os path exists pwd file pwds pickle load open pwd file rb else pwds save to disk pickle dump pwds open pwd file wb add password pwds username hashlib sha password hexdigest check password if pwds username hashlib sha password hexdigest print good else print no match note that this stores the passwords as hash so they are essentially unrecoverable if you lose your password you would get allocated new one not get the old one back
QA
python user input and commandline arguments how do have python script that can accept user input assuming this is possible and how do make it read in arguments if run from the command line
to read user input you can try the cmd module for easily creating mini command line interpreter with help texts and autocompletion and raw input for less fancy stuff just reading line of text from the user command line inputs are in sys argv try this in your script for python import sys print sys argv for python import sys print sys argv since print has changed from keyword in python into function call in python there are two modules for parsing command line options optparse and getopt if you just want to input files to your script behold the power of fileinput the python library reference is your friend
QA
python user input and commandline arguments how do have python script that can accept user input assuming this is possible and how do make it read in arguments if run from the command line
use raw input for input from console terminal if you just want command line argument like file name or something python my prog py file name txt then you can use sys argv import sys print sys argv sys argv is list where is the program name so in the above example sys argv would be file name txt if you want to have full on command line options use the optparse module pev
QA
python user input and commandline arguments how do have python script that can accept user input assuming this is possible and how do make it read in arguments if run from the command line
careful not to use the input function unless you know what you are doing unlike raw input input will accept any python expression so it is kind of like eval
QA
libxml on os needs sudo when trying to use libxml as myself get an error saying the package cannot be found if run as as super user am able to import fine have installed python and all libxml and libxml py related libraries via fink and own the entire path including the library any ideas why would still need to sudo
would suspect the permissions on the library can you do strace or similar to find out the filenames it is looking for and then check the permissions on them
QA
python psycopg error and connection handling mysqldb is there way to make psycopg and postgres deal with errors without having to reestablish the connection like mysqldb the commented version of the below works with mysqldb the comments make it work with psycopg results felicitas volumes acillevs mosaics perat xe representative for item in sorted results try cur execute insert into resultstab values item results item print item results item conn commit except conn psycopg connect user bvm database wdb password redacted cur conn cursor print choked on item continue this must slow things down could anyone give suggestion for passing over formatting errors obviously the above chokes on apostrophes but is there way to make it pass over that without getting something like the following or committing reconnecting etc agreement agreements agrees agrippa choked on agrippa choked on agrippina
think your code looks like this at the moment very long text split for in cursor execute insert into yourtable yourcol values so try to change it into something like this very long text split for in cursor execute insert into yourtable yourcol values so never forget to pass your parameters in the parameters list then you do not have to care about your quotes and stuff it is also more secure you can read more about it at http www python org dev peps pep also have look there at the method executemany which is specially designed to execute the same statement multiple times
QA
why are python private methods not actually private python gives us the ability to create private methods and variables within class by prepending double underscores to the name like this myprivatemethod how then can one explain this class myclass def mypublicmethod self print public method def myprivatemethod self print this is private obj myclass obj mypublicmethod public method obj myprivatemethod traceback most recent call last file line in attributeerror myclass instance has no attribute myprivatemethod dir obj myclass myprivatemethod doc module mypublicmethod obj myclass myprivatemethod this is private what is the deal will explain this little for those who did not quite get that class myclass def mypublicmethod self print public method def myprivatemethod self print this is private obj myclass what did there is create class with public method and private method and instantiate it next call its public method obj mypublicmethod public method next try and call its private method obj myprivatemethod traceback most recent call last file line in attributeerror myclass instance has no attribute myprivatemethod everything looks good here we are unable to call it it is in fact private well actually it is not running dir on the object reveals new magical method that python creates magically for all of your private methods dir obj myclass myprivatemethod doc module mypublicmethod this new method name is always an underscore followed by the class name followed by the method name obj myclass myprivatemethod this is private so much for encapsulation eh in any case would always heard python does not support encapsulation so why even try what gives
the name scrambling is used to ensure that subclasses do not accidentally override the private methods and attributes of their superclasses it is not designed to prevent deliberate access from outside for example class foo object def init self self baz def foo self print self baz class bar foo def init self super bar self init self baz def bar self print self baz bar foo bar print dict bar baz foo baz of course it breaks down if two different classes have the same name
QA
python authentication api am looking for python library that will help me to create an authentication method for desktop app am writing have found several method in web framework such as django or turbogears just want kind of username password association stored into local file can write it by myself but am really it already exists and will be better solution am not very fluent with encryption
treat the following as pseudo code try from hashlib import sha as hasher except importerror you could probably exclude the try except bit but older python distros do not have hashlib try import sha as hasher except importerror import md as hasher def hash password password returns the hashed version of string return hasher new str password hexdigest def load auth file path loads comma seperated file important make sure the username does not contain any commas open the file or return an empty auth list try open path except ioerror print warning auth file not found return ret for line in readlines split line line split if len split line print warning malformed line print split line continue skip it else username password split line ret username password end if end for return ret def main auth file home blah myauth txt you raw input username raw input password getpass is probably better if auth file has key you strip if auth file you hash password the hash matches the stored one print welcome sir instead of using comma separated file would recommend using sqlite which could be used for other settings and such also remember that this is not very secure if the application is local evil users could probably just replace the myauth txt file local application auth is difficult to do well you will have to encrypt any data it reads using the users password and generally be very careful
QA
are tuples more efficient than lists in python is there any performance difference between tuples and lists when it comes to instantiation and retrieval of elements
tuples being immutable are more memory efficient lists for efficiency overallocate memory in order to allow appends without constant reallocs so if you want to iterate through constant sequence of values in your code eg for direction in up right down left tuples are preferred since such tuples are pre calculated in compile time access speeds should be the same they are both stored as contiguous arrays in the memory but alist append item is much preferred to atuple item when you deal with mutable data remember tuples are intended to be treated as records without field names
QA
html parser in python using the python documentation found the html parser but have no idea which library to import to use it how do find this out bearing in mind it does not say on the page
try import htmlparser in python the htmlparser module has been renamed to html parser you can check about this here python import html parser python and above import htmlparser
QA
html parser in python using the python documentation found the html parser but have no idea which library to import to use it how do find this out bearing in mind it does not say on the page
there is link to an example on the bottom of http docs python org library htmlparser html it just does not work with the original python or python it has to be python as it says on the top
QA
html parser in python using the python documentation found the html parser but have no idea which library to import to use it how do find this out bearing in mind it does not say on the page
you probably really want beautifulsoup check the link for an example but in any case import htmlparser htmlparser htmlparser feed html html get starttag text html close
QA
html parser in python using the python documentation found the html parser but have no idea which library to import to use it how do find this out bearing in mind it does not say on the page
would recommend using beautiful soup module instead and it has good documentation
QA
html parser in python using the python documentation found the html parser but have no idea which library to import to use it how do find this out bearing in mind it does not say on the page
for real world html processing would recommend beautifulsoup it is great and takes away much of the pain installation is easy
QA
are tuples more efficient than lists in python is there any performance difference between tuples and lists when it comes to instantiation and retrieval of elements
you should also consider the array module in the standard library if all the items in your list or tuple are of the same type it can be faster and take less memory
QA
html parser in python using the python documentation found the html parser but have no idea which library to import to use it how do find this out bearing in mind it does not say on the page
you should also look at html lib for python as it tries to parse html in way that very much resembles what web browsers do especially when dealing with invalid html which is more than of today web
QA
html parser in python using the python documentation found the html parser but have no idea which library to import to use it how do find this out bearing in mind it does not say on the page
do not recommend beautifulsoup if you want speed lxml is much much faster and you can fall back in lxml bs soupparser if the default parser does not work
QA
using the docstring from one method to automatically overwrite that of another method the problem have class which contains template method execute which calls another method execute subclasses are supposed to overwrite execute to implement some specific functionality this functionality should be documented in the docstring of execute advanced users can create their own subclasses to extend the library however another user dealing with such subclass should only use execute so he will not see the correct docstring if he uses help execute therefore it would be nice to modify the base class in such way that in subclass the docstring of execute is automatically replaced with that of execute any ideas how this might be done was thinking of metaclasses to do this to make this completely transparent to the user
well the doc string is stored in doc so it would not be too hard to re assign it based on the doc string of execute after the fact basically class myclass object def execute self original doc string self execute class subclass myclass def execute self sub class doc string pass re assign doc string of execute def execute self args kw return myclass execute args kw execute doc execute doc execute has to be re declared to that the doc string gets attached to the version of execute for the subclass and not for myclass which would otherwise interfere with other sub classes that is not very tidy way of doing it but from the pov of the user of library it should give the desired result you could then wrap this up in meta class to make it easier for people who are sub classing
QA
serving dynamically generated zip archives in django how to serve users dynamically generated zip archive in django am making site where users can choose any combination of available books and download them as zip archive am worried that generating such archives for each request would slow my server down to crawl have also heard that django does not currently have good solution for serving dynamically generated files
the solution is as follows use python module zipfile to create zip archive but as the file specify stringio object zipfile constructor requires file like object add files you want to compress then in your django application return the content of stringio object in httpresponse with mimetype set to application zip compressed or at least application octet stream if you want you can set content disposition header but this should not be really required but beware creating zip archives on each request is bad idea and this may kill your server not counting timeouts if the archives are large performance wise approach is to cache generated output somewhere in filesystem and regenerate it only if source files have changed even better idea is to prepare archives in advance eg by cron job and have your web server serving them as usual statics
QA
using the docstring from one method to automatically overwrite that of another method the problem have class which contains template method execute which calls another method execute subclasses are supposed to overwrite execute to implement some specific functionality this functionality should be documented in the docstring of execute advanced users can create their own subclasses to extend the library however another user dealing with such subclass should only use execute so he will not see the correct docstring if he uses help execute therefore it would be nice to modify the base class in such way that in subclass the docstring of execute is automatically replaced with that of execute any ideas how this might be done was thinking of metaclasses to do this to make this completely transparent to the user
is there reason you cannot override the base class execute function directly class base object def execute self class derived base def execute self docstring for derived class base execute self stuff specific to derived if you do not want to do the above method objects do not support writing to the doc attribute so you have to change doc in the actual function object since you do not want to override the one in the base class you would have to give each subclass its own copy of execute class derived base def execute self return base execute self class execute self docstring for subclass execute doc execute doc but this is similar to roundabout way of redefining execute
QA
how to generate urls in django in django template language you can use url viewname args to generate url to specific view with parameters how can you programatically do the same in python code what need is to create list of menu items where each item has name url and an active flag whether it is the current page or not this is because it will be lot cleaner to do this in python than the template language
be aware that using reverse requires that your urlconf module is error free and can be processed iow no viewdoesnotexist errors or so or you get the dreaded noreversematch exception errors in templates usually fail silently resulting in none
QA
using django time date widgets in custom form how can use the nifty javascript date and time widgets that the default admin uses with my custom view have looked through the django forms documentation and it briefly mentions django contrib admin widgets but do not know how to use it here is my template that want it applied on form action method post table for in form tr td name td td td tr endfor table input type submit name submit value add product form also think it should be noted that have not really written view up myself for this form am using generic view here is the entry from the url py admin products add create object model product post save redirect and am relevantly new to the whole django mvc mtv thing so please go easy
as the solution is hackish think using your own date time widget with some javascript is more feasible
QA
updating an auto now datetimefield in parent model django have got two models message and attachment each attachment is attached to specific message using foreignkey on the attachment model both models have an auto now datetimefield called updated am trying to make it so that when any attachment is saved it also sets the updated field on the associated message to now here is my code def save self super attachment self save self message updated self updated will this work and if you can explain it to me why if not how would accomplish this
datetime fields with auto now are automatically updated upon calling save so you do not need to update them manually django will do this work for you
QA
python and re tutorial have on regex in python explains how to use the re module in python wanted to grab the url out of an tag so knowing regex wrote the correct expression and tested it in my regex testing app of choice and ensured it worked when placed into python it failed after much head scratching found out the issue it automatically expects your pattern to be at the start of the string have found fix but would like to know how to change regex regex of pure awesomeness into regex regex of pure awesomeness okay it is standard url regex but wanted to avoid any potential confusion about what wanted to get rid of and possibly pretend to be funny
are you using the re match or re search method my understanding is that re match assumes at the begining of your expression and will only search at the beginning of the text while re search acts more like the perl regular expressions and will only match the beginning of the text if you include at the beginning of your expression hope that helps
QA
python and re tutorial have on regex in python explains how to use the re module in python wanted to grab the url out of an tag so knowing regex wrote the correct expression and tested it in my regex testing app of choice and ensured it worked when placed into python it failed after much head scratching found out the issue it automatically expects your pattern to be at the start of the string have found fix but would like to know how to change regex regex of pure awesomeness into regex regex of pure awesomeness okay it is standard url regex but wanted to avoid any potential confusion about what wanted to get rid of and possibly pretend to be funny
in python there is distinction between match and search match only looks for the pattern at the start of the string and search looks for the pattern starting at any location within the string python regex docs matching vs searching
QA
python unittest logic can someone explain this result to me the first test succeeds but the second fails although the variable tested is changed in the first test class mytest unittest testcase def setup self self def testa self self self assertequal self def testb self self assertequal self unittest main fail testb main mytest traceback most recent call last file pyshell line in testb assertionerror ran tests in
if recall correctly in that test framework the setup method is run before each test
QA
python and re tutorial have on regex in python explains how to use the re module in python wanted to grab the url out of an tag so knowing regex wrote the correct expression and tested it in my regex testing app of choice and ensured it worked when placed into python it failed after much head scratching found out the issue it automatically expects your pattern to be at the start of the string have found fix but would like to know how to change regex regex of pure awesomeness into regex regex of pure awesomeness okay it is standard url regex but wanted to avoid any potential confusion about what wanted to get rid of and possibly pretend to be funny
import re pattern re compile url string url pattern match string pattern search string sre sre match object at xb
QA
python unittest logic can someone explain this result to me the first test succeeds but the second fails although the variable tested is changed in the first test class mytest unittest testcase def setup self self def testa self self self assertequal self def testb self self assertequal self unittest main fail testb main mytest traceback most recent call last file pyshell line in testb assertionerror ran tests in
from http docs python org lib minimal example html when setup method is defined the test runner will run that method prior to each test so setup gets run before both testa and testb setting to each time behind the scenes the entire test object is actually being re instantiated for each test with setup being run on each new instantiation before the test is executed
QA
python and re tutorial have on regex in python explains how to use the re module in python wanted to grab the url out of an tag so knowing regex wrote the correct expression and tested it in my regex testing app of choice and ensured it worked when placed into python it failed after much head scratching found out the issue it automatically expects your pattern to be at the start of the string have found fix but would like to know how to change regex regex of pure awesomeness into regex regex of pure awesomeness okay it is standard url regex but wanted to avoid any potential confusion about what wanted to get rid of and possibly pretend to be funny
you are probably being tripped up by the different methods re search and re match
QA
using the docstring from one method to automatically overwrite that of another method the problem have class which contains template method execute which calls another method execute subclasses are supposed to overwrite execute to implement some specific functionality this functionality should be documented in the docstring of execute advanced users can create their own subclasses to extend the library however another user dealing with such subclass should only use execute so he will not see the correct docstring if he uses help execute therefore it would be nice to modify the base class in such way that in subclass the docstring of execute is automatically replaced with that of execute any ideas how this might be done was thinking of metaclasses to do this to make this completely transparent to the user
well if you do not mind copying the original method in the subclass you can use the following technique import new def copyfunc func return new function func func code func func globals func func name func func defaults func func closure class metaclass type def new meta name bases attrs for key in attrs keys if key skey key for base in bases original getattr base skey none if original is not none copy copyfunc original copy doc attrs key doc attrs skey copy break return type new meta name bases attrs class class object metaclass metaclass def execute self original doc string return self execute class subclass class def execute self sub class doc string pass
QA
using the docstring from one method to automatically overwrite that of another method the problem have class which contains template method execute which calls another method execute subclasses are supposed to overwrite execute to implement some specific functionality this functionality should be documented in the docstring of execute advanced users can create their own subclasses to extend the library however another user dealing with such subclass should only use execute so he will not see the correct docstring if he uses help execute therefore it would be nice to modify the base class in such way that in subclass the docstring of execute is automatically replaced with that of execute any ideas how this might be done was thinking of metaclasses to do this to make this completely transparent to the user
agree that the simplest most pythonic way of approaching this is to simply redefine execute in your subclasses and have it call the execute method of the base class class sub base def execute self new docstring goes here return base execute self this is very little code to accomplish what you want the only downside is that you must repeat this code in every subclass that extends base however this is small price to pay for the behavior you want if you want sloppy and verbose way of making sure that the docstring for execute is dynamically generated you can use the descriptor protocol which would be significantly less code than the other proposals here this is annoying because you cannot just set descriptor on an existing function which means that execute must be written as separate class with call method here is the code to do this but keep in mind that my above example is much simpler and more pythonic class executor object doc property lambda self self inst execute doc def call self return self inst execute class base object execute executor class sub base def init self self execute inst self def execute self actually does something return hello world spam sub print spam execute doc prints actually does something help spam the execute method says actually does something
QA
how do sort list of dictionaries by values of the dictionary in python got list of dictionaries and want that to be sorted by value of that dictionary this name homer age name bart age sorted by name should become name bart age name homer age
you have to implement your own comparison function that will compare the dictionaries by values of name keys see sorting mini how to from pythoninfo wiki
QA
mod python mysql error on insert with lot of data operationalerror mysql server has gone away when doing an insert with lot of data ie insert into table mediumtext field values lots of text here about mb worth mysql returns operationalerror mysql server has gone away this is happening within minute of starting the script so it is not timeout issue also mediumtext field should be able to hold mb of data so that should not be problem any ideas what is causing the error or how to work around it some relevant libraries being used mod python mysql on windows xp sp via xampp details below apachefriends xampp basic package version apache mysql phpmyadmin
check the max packet setting in your my cnf file this determines the largest amount of data you can send to your mysql server in single statement exceeding this values results in that error
QA
how do sort list of dictionaries by values of the dictionary in python got list of dictionaries and want that to be sorted by value of that dictionary this name homer age name bart age sorted by name should become name bart age name homer age
guess you have meant name homer age name bart age this would be sorted like this sorted cmp lambda cmp name name
QA
how do sort list of dictionaries by values of the dictionary in python got list of dictionaries and want that to be sorted by value of that dictionary this name homer age name bart age sorted by name should become name bart age name homer age
my list name homer age name bart age my list sort lambda cmp name name my list will now be what you want years later edited to add the new key argument is more efficient and neater better answer now looks like my list sorted my list key lambda name the lambda is am going to easier to understand than operator itemgetter but ymmv
QA
how do sort list of dictionaries by values of the dictionary in python got list of dictionaries and want that to be sorted by value of that dictionary this name homer age name bart age sorted by name should become name bart age name homer age
it may look cleaner using key instead cmp newlist sorted list to be sorted key lambda name or as sebastian and others suggested from operator import itemgetter newlist sorted list to be sorted key itemgetter name for completeness as pointed out in comments by fitzgeraldsteele add reverse true to sort descending newlist sorted key itemgetter name reverse true
QA
how do sort list of dictionaries by values of the dictionary in python got list of dictionaries and want that to be sorted by value of that dictionary this name homer age name bart age sorted by name should become name bart age name homer age
import operator list of dicts sort key operator itemgetter name key is used to sort by an arbitrary value and itemgetter sets that value to each item name attribute
QA
how to do relative imports in python imagine this directory structure app init py sub init py mod py sub init py mod py am coding mod and need to import something from mod how should do it tried from sub import mod but am getting an attempted relative import in non package googled around but found only sys path manipulation hacks is not there clean way edit all my init py are currently empty edit am trying to do this because sub contains classes that are shared across sub packages sub subx etc edit the behaviour am looking for is the same as described in pep thanks john
everyone seems to want to tell you what you should be doing rather than just answering the question the problem is that you are running the module as main by passing the mod py as an argument to the interpreter from pep relative imports use module name attribute to determine that module position in the package hierarchy if the module name does not contain any package information it is set to main then relative imports are resolved as if the module were top level module regardless of where the module is actually located on the file system in python they are adding the ability to reference modules relative to the main module pep describes the change update according to nick coghlan the recommended alternative is to run the module inside the package using the switch
QA
how to create triple join table with django using django built in models how would one create triple join between three models for example users roles and events are the models users have many roles and roles many users manytomany events have many users and users many events manytomany but for any given event any user may have only one role how can this be represented in the model
would recommend just creating an entirely separate model for this class assignment model user foreignkey user role foreignkey role event foreignkey event this let us you do all the usual model stuff such as user assignment set filter role name chaperon role assignment set filter event name silly walkathon the only thing left is to enforce your one role per user per event restriction you can do this in the assignment class by either overriding the save method http docs djangoproject com en dev topics db models overriding predefined model methods or using signals http docs djangoproject com en dev topics signals
QA
how do sort list of dictionaries by values of the dictionary in python got list of dictionaries and want that to be sorted by value of that dictionary this name homer age name bart age sorted by name should become name bart age name homer age
you could use custom comparison function or you could pass in function that calculates custom sort key that is usually more efficient as the key is only calculated once per item while the comparison function would be called many more times you could do it this way def mykey adict return adict name name homer age name bart age sorted key mykey but the standard library contains generic routine for getting items of arbitrary objects itemgetter so try this instead from operator import itemgetter name homer age name bart age sorted key itemgetter name
QA
convert bytes to floating point numbers in python have binary file that have to parse and am using python is there way to take bytes and convert it to single precision floating point number
import struct struct pack xdb fi struct unpack xdb fi struct pack
QA
is there way around coding in python without the tab indent whitespace criteria want to start using python for small projects but the fact that misplaced tab or indent can throw compile error is really getting on my nerves is there some type of setting to turn this off am currently using notepad is there maybe an ide that would take care of the tabs and indenting
strange no one mentioned gedit gnome or openkomodo windows mac gnu linux both of them are great openkomodo especially deals with tabs and spaces very well and it is free whee when need lighter weight thingy just use gedit download openkomodo here http www openkomodo com
QA
how do sort list of dictionaries by values of the dictionary in python got list of dictionaries and want that to be sorted by value of that dictionary this name homer age name bart age sorted by name should become name bart age name homer age
import operator to sort the list of dictionaries by key name list of dicts sort key operator itemgetter name to sort the list of dictionaries by key age list of dicts sort key operator itemgetter age
QA
using the docstring from one method to automatically overwrite that of another method the problem have class which contains template method execute which calls another method execute subclasses are supposed to overwrite execute to implement some specific functionality this functionality should be documented in the docstring of execute advanced users can create their own subclasses to extend the library however another user dealing with such subclass should only use execute so he will not see the correct docstring if he uses help execute therefore it would be nice to modify the base class in such way that in subclass the docstring of execute is automatically replaced with that of execute any ideas how this might be done was thinking of metaclasses to do this to make this completely transparent to the user
look at the functools wraps decorator it does all of this but do not know offhand if you can get it to run in the right context
QA
is there python package to interface with ms cluster need to write couple of python scripts to automate the installation of microsoft cluster ressources more specifically will need to query ms cluster to be able to get list of ressources with their parameters and also need to be able to create resources and set their parameters is someone knows if there is package module or even some sample scripts using mark hammond pywin packages
you can accomplish this using microsoft com objects you can take look at here on how to start using them
QA
serving dynamically generated zip archives in django how to serve users dynamically generated zip archive in django am making site where users can choose any combination of available books and download them as zip archive am worried that generating such archives for each request would slow my server down to crawl have also heard that django does not currently have good solution for serving dynamically generated files
suggest to use separate model for storing those temp zip files you can create zip on fly save to model with filefield and finally send url to user advantages serving static zip files with django media mechanism like usual uploads ability to cleanup stale zip files by regular cron script execution which can use date field from zip file model
QA
terminating python script am aware of the die command in php which stops script early how can do this in python
import sys sys exit details from the sys module documentation sys exit arg exit from python this is implemented by raising the systemexit exception so cleanup actions specified by finally clauses of try statements are honored and it is possible to intercept the exit attempt at an outer level the optional argument arg can be an integer giving the exit status defaulting to zero or another type of object if it is an integer zero is considered successful termination and any nonzero value is considered abnormal termination by shells and the like most systems require it to be in the range and produce undefined results otherwise some systems have convention for assigning specific meanings to specific exit codes but these are generally underdeveloped unix programs generally use for command line syntax errors and for all other kind of errors if another type of object is passed none is equivalent to passing zero and any other object is printed to stderr and results in an exit code of in particular sys exit some error message is quick way to exit program when an error occurs since exit ultimately only raises an exception it will only exit the process when called from the main thread and the exception is not intercepted note that this is the nice way to exit glyphtwistedmatrix below points out that if you want hard exit you can use os exit errorcode though it is likely os specific to some extent it might not take an errorcode under windows for example and it definitely is less friendly since it does not let the interpreter do any cleanup before the process dies
QA
terminating python script am aware of the die command in php which stops script early how can do this in python
another way is raise systemexit
QA
terminating python script am aware of the die command in php which stops script early how can do this in python
from sys import exit exit as parameter you can pass an exit code which will be returned to os default is
QA
python unittest logic can someone explain this result to me the first test succeeds but the second fails although the variable tested is changed in the first test class mytest unittest testcase def setup self self def testa self self self assertequal self def testb self self assertequal self unittest main fail testb main mytest traceback most recent call last file pyshell line in testb assertionerror ran tests in
each test is run using new instance of the mytest class that means if you change self in one test changes will not carry over to other tests since self will refer to different instance additionally as others have pointed out setup is called before each test
QA
sending mail via sendmail from python if want to send mail not via smtp but rather via sendmail is there library for python that encapsulates this process better yet is there good library that abstracts the whole sendmail versus smtp choice will be running this script on bunch of unix hosts only some of which are listening on localhost few of these are part of embedded systems and cannot be set up to accept smtp as part of good practice would really like to have the library take care of header injection vulnerabilities itself so just dumping string to popen usr bin sendmail is little closer to the metal than would like if the answer is go write library so be it
it is quite common to just use the sendmail command from python using os popen personally for scripts did not write myself think just using the smtp protocol is better since it would not require installing say an sendmail clone to run on windows https docs python org library smtplib html
QA
sending mail via sendmail from python if want to send mail not via smtp but rather via sendmail is there library for python that encapsulates this process better yet is there good library that abstracts the whole sendmail versus smtp choice will be running this script on bunch of unix hosts only some of which are listening on localhost few of these are part of embedded systems and cannot be set up to accept smtp as part of good practice would really like to have the library take care of header injection vulnerabilities itself so just dumping string to popen usr bin sendmail is little closer to the metal than would like if the answer is go write library so be it
this is simple python function that uses the unix sendmail to deliver mail def sendmail sendmail location usr sbin sendmail sendmail location os popen sendmail location write from from somewhere com write to to somewhereelse com write subject thesubject write blank line separating headers from body write body of the mail status close if status print sendmail exit status status
QA
sending mail via sendmail from python if want to send mail not via smtp but rather via sendmail is there library for python that encapsulates this process better yet is there good library that abstracts the whole sendmail versus smtp choice will be running this script on bunch of unix hosts only some of which are listening on localhost few of these are part of embedded systems and cannot be set up to accept smtp as part of good practice would really like to have the library take care of header injection vulnerabilities itself so just dumping string to popen usr bin sendmail is little closer to the metal than would like if the answer is go write library so be it
header injection is not factor in how you send the mail it is factor in how you construct the mail check the email package construct the mail with that serialise it and send it to usr sbin sendmail using the subprocess module from email mime text import mimetext from subprocess import popen pipe message mimetext here is the body of my message message from me example com message to you example com message subject this is the subject popen usr sbin sendmail oi stdin pipe communicate message as string
QA
is there common way to check in python if an object is any function type have function in python which is iterating over the attributes returned from dir obj and want to check to see if any of the objects contained within is function method built in function etc normally you could use callable for this but do not want to include classes the best have come up with so far is isinstance obj types builtinfunctiontype types functiontype types methodtype is there more future proof way to do this check edit misspoke before when said normally you could use callable for this but do not want to disqualify classes actually do want to disqualify classes want to match only functions not classes
if hasattr obj call pass this also fits in better with python duck typing philosophy because you do not really care what it is so long as you can call it it is worth noting that callable is being removed from python and is not present in
QA
is there common way to check in python if an object is any function type have function in python which is iterating over the attributes returned from dir obj and want to check to see if any of the objects contained within is function method built in function etc normally you could use callable for this but do not want to include classes the best have come up with so far is isinstance obj types builtinfunctiontype types functiontype types methodtype is there more future proof way to do this check edit misspoke before when said normally you could use callable for this but do not want to disqualify classes actually do want to disqualify classes want to match only functions not classes
if you want to exclude classes and other random objects that may have call method and only check for functions and methods these three functions in the inspect module inspect isfunction obj inspect isbuiltin obj inspect ismethod obj should do what you want in future proof way
QA
why java and python garbage collection methods are different python uses the reference count method to handle object life time so an object that has no more use will be immediately destroyed but in java the gc garbage collector destroys objects which are no longer used at specific time why does java choose this strategy and what is the benefit from this is this better than the python approach
garbage collection is faster more time efficient than reference counting if you have enough memory for example copying gc traverses the live objects and copies them to new space and can reclaim all the dead objects in one step by marking whole memory region this is very efficient if you have enough memory generational collections use the knowledge that most objects die young often only few percent of objects have to be copied this is also the reason why gc can be faster than malloc free reference counting is much more space efficient than garbage collection since it reclaims memory the very moment it gets unreachable this is nice when you want to attach finalizers to objects to close file once the file object gets unreachable reference counting system can work even when only few percent of the memory is free but the management cost of having to increment and decrement counters upon each pointer assignment cost lot of time and some kind of garbage collection is still needed to reclaim cycles so the trade off is clear if you have to work in memory constrained environment or if you need precise finalizers use reference counting if you have enough memory and need the speed use garbage collection
QA
random in python not working am trying to use the import random statement in python but it does not appear to have any methods in it to use am missing something
think you need to give some more information it is not really possible to answer why it is not working based on the information in the question the basic documentation for random is at https docs python org library random html you might check there
QA
continuous integration system for python codebase am starting work on hobby project with python codebase and would like to set up some form of continuous integration running battery of test cases each time check in is made and sending nag mails to responsible persons when the tests fail similar to cruisecontrol or teamcity realize could do this with hooks in most vcses but that requires that the tests run on the same machine as the version control server which is not as elegant as would like does anyone have any suggestions for small user friendly open source continuous integration system suitable for python codebase
we are using bitten wich is integrated with trac and it is python based
QA
random in python not working am trying to use the import random statement in python but it does not appear to have any methods in it to use am missing something
can you post an example of what you are trying to do it is not clear from your question what the actual problem is here is an example of how to use the random module import random print random randint
QA
random in python not working am trying to use the import random statement in python but it does not appear to have any methods in it to use am missing something
python jun gcc pre on linux type help copyright credits or license for more information import random random seed dir random bpf log nv magicconst recip bpf random sg magicconst systemrandom twopi wichmannhill builtinmethodtype methodtype all builtins doc file name acos ceil cos exp hexlify inst log pi random sin sqrt test test generator urandom warn betavariate choice expovariate gammavariate gauss getrandbits getstate jumpahead lognormvariate normalvariate paretovariate randint random randrange sample seed setstate shuffle uniform vonmisesvariate weibullvariate random randint random randint
QA
random in python not working am trying to use the import random statement in python but it does not appear to have any methods in it to use am missing something
seems to work fine for me check out the methods in the official python documentation for random import random random random random uniform random randint
QA
cross platform ipc am looking for suggestions on possible ipc mechanisms that are cross platform win and linux at least simple to implement in as well as the most common scripting languages perl ruby python etc finally simple to use from programming point of view what are my options am programming under linux but would like what write to be portable to other oses in the future have thought about using sockets named pipes or something like dbus does anyone have any advice
why not bus it is very simple message passing system that runs on almost all platforms and is designed for robustness it is supported by pretty much every scripting language at this point http freedesktop org wiki software dbus
QA
cross platform ipc am looking for suggestions on possible ipc mechanisms that are cross platform win and linux at least simple to implement in as well as the most common scripting languages perl ruby python etc finally simple to use from programming point of view what are my options am programming under linux but would like what write to be portable to other oses in the future have thought about using sockets named pipes or something like dbus does anyone have any advice
python has pretty good ipc library see https docs python org library ipc html