content
stringlengths
85
101k
title
stringlengths
0
150
question
stringlengths
15
48k
answers
list
answers_scores
list
non_answers
list
non_answers_scores
list
tags
list
name
stringlengths
35
137
Q: How to make XPath select multiple table elements with identical id attributes? I'm currently trying to extract information from a badly formatted web page. Specifically, the page has used the same id attribute for multiple table elements. The markup is equivalent to something like this: <body> <div id="random_...
How to make XPath select multiple table elements with identical id attributes?
I'm currently trying to extract information from a badly formatted web page. Specifically, the page has used the same id attribute for multiple table elements. The markup is equivalent to something like this: <body> <div id="random_div"> <p>Some content.</p> <table id="table_1"> <tr> ...
[ "With Firebug, this expression:\n//table[@id='table_1']//td/text()\n\ngives me this:\n[<TextNode textContent=\"Important text 1.\">,\n <TextNode textContent=\"Important text 2.\">,\n <TextNode textContent=\"Important text 3.\">,\n <TextNode textContent=\"Important text 4.\">,\n <TextNode textContent=\"Important tex...
[ 1, 0 ]
[]
[]
[ "html_parsing", "python", "scrapy", "web_scraping", "xpath" ]
stackoverflow_0007888429_html_parsing_python_scrapy_web_scraping_xpath.txt
Q: Two word token using PLY in Python I am writing a compiler as part of a lab excercise and have chosen to do it in Python using PLY. I have spent some time trying to work this particular problem out and have reached a dead end as have my lab helpers. In the language I have to write, declarators are specified with t...
Two word token using PLY in Python
I am writing a compiler as part of a lab excercise and have chosen to do it in Python using PLY. I have spent some time trying to work this particular problem out and have reached a dead end as have my lab helpers. In the language I have to write, declarators are specified with two words "was a". For example: x was a n...
[ "You should never have to use two words in a token. Instead split them into two seperate tokens and ensure your language enforces that one is always followed by the other.\ne.g. implement a 'was' : 'DECLARATOR_WAS' token and an 'a' : 'DECLARATOR_A' token.\n" ]
[ 3 ]
[]
[]
[ "compiler_construction", "lexer", "ply", "python" ]
stackoverflow_0007887438_compiler_construction_lexer_ply_python.txt
Q: plone 4.1 - plone.app.caching issue - unable to reduce http requests Problem: I'd like to reduce the number of http request just by caching in browser some resources. I've succesfully configured plone.app.caching in plone4.1 (without caching proxy), and no debug/develop mode (css, js, kss) is active. I'm getting c...
plone 4.1 - plone.app.caching issue - unable to reduce http requests
Problem: I'd like to reduce the number of http request just by caching in browser some resources. I've succesfully configured plone.app.caching in plone4.1 (without caching proxy), and no debug/develop mode (css, js, kss) is active. I'm getting correct "X-Cache-Operation" headers in responses, but the number of http re...
[ "Firebug shows all resource responses, including those taken from the browser cache. The way to differentiate between the two is the colour of the entry; black means it required network access (e.g. the browser asked the server), gray is a cached response.\nIn other words, just because you see resources listed in F...
[ 1 ]
[]
[]
[ "caching", "plone", "python" ]
stackoverflow_0007887707_caching_plone_python.txt
Q: Using POSIX to exclude a word inside a string Is it possible to use ONLY POSIX regular expressions to guarantee that a word does not appear inside a string?? I mean that, if i wanted to have only words that dont have "tree": It should tell me that "I like turtles" matches. On the other hand, it should not match "T...
Using POSIX to exclude a word inside a string
Is it possible to use ONLY POSIX regular expressions to guarantee that a word does not appear inside a string?? I mean that, if i wanted to have only words that dont have "tree": It should tell me that "I like turtles" matches. On the other hand, it should not match "The man is on the tree" Thanks
[ "^([^t]|(t[^r])|(tr[^e])|(tre[^e]))*($|(t($|(r($|e$)))))\n\n", "There are many ways to do it without using Python. \nLets assume that you have stored your data in a textfile. This should do the trick:\ngrep '\\tree\\>' textfile \n\n" ]
[ 4, 0 ]
[]
[]
[ "posix", "python", "regex" ]
stackoverflow_0007883819_posix_python_regex.txt
Q: distutils setup install --build-base doesn't work This doesn't work: python setup.py install --build-base=foo How can I tell distutils where to take the built files from for installation? A: I found this bug report in python's Issue Tracker. It suggests: python setup.py build -b <somedir> install And it works ...
distutils setup install --build-base doesn't work
This doesn't work: python setup.py install --build-base=foo How can I tell distutils where to take the built files from for installation?
[ "I found this bug report in python's Issue Tracker. It suggests:\npython setup.py build -b <somedir> install\n\nAnd it works for me.\n" ]
[ 5 ]
[]
[]
[ "build", "distutils", "installation", "python" ]
stackoverflow_0007888763_build_distutils_installation_python.txt
Q: How do I call IBM IMM methods using SOAPpy? I'm trying to use SOAPpy to call various SOAP methods of an IBM IMM (Integrated Management Module). Unfortunately I'm rather new to SOAP and can't figure it out at all. I don't have any kind of WSDL, so I've had to resort to watching to see what my browser does when it m...
How do I call IBM IMM methods using SOAPpy?
I'm trying to use SOAPpy to call various SOAP methods of an IBM IMM (Integrated Management Module). Unfortunately I'm rather new to SOAP and can't figure it out at all. I don't have any kind of WSDL, so I've had to resort to watching to see what my browser does when it makes the various requests. The actual call that's...
[ "it will be much better to use the WSDL file on the remote server to specify the methods (functions) and their corresponding parameters and data types.\nAdditionally, you will have the opportunity to know exactly the name space, encoding and formatting of the SOAP connection to be established.\nTry using:\nSERVER=S...
[ 0 ]
[]
[]
[ "python", "soap", "soappy" ]
stackoverflow_0006049235_python_soap_soappy.txt
Q: Python Java Cross communication Servers +-------------------+ +-------------------+ | Wowza | | Django | |-------------------| |-------------------| +-------------+ | | | ...
Python Java Cross communication Servers
+-------------------+ +-------------------+ | Wowza | | Django | |-------------------| |-------------------| +-------------+ | | | | | | | ...
[ "Any RPC will be able to solve the above for you. I have not used DjangoAMF so can't comment on that. You can also expose some sort of REST API on both servers for this purpose.\n" ]
[ 0 ]
[]
[]
[ "communication", "cross_language", "java", "python" ]
stackoverflow_0007888695_communication_cross_language_java_python.txt
Q: Guaranteeing a file close I have a class where I create a file object in the constructor. This class also implements a finish() method as part of its interface and in this method I close the file object. The problem is that if I get an exception before this point, the file will not be closed. The class in question...
Guaranteeing a file close
I have a class where I create a file object in the constructor. This class also implements a finish() method as part of its interface and in this method I close the file object. The problem is that if I get an exception before this point, the file will not be closed. The class in question has a number of other methods ...
[ "You could make your class a context-manager, and then wrap object creation and use of that class in a with-statement. See PEP 343 for details.\nTo make your class a context-manager, it has to implement the methods __enter__() and __exit__(). __enter__() is called when you enter the with-statement, and __exit__() i...
[ 11, 3, 1 ]
[]
[]
[ "python" ]
stackoverflow_0007888953_python.txt
Q: How can I edit a secondary calendar using google python API I wonder if it's possible to create and delete events with Google API in a secondary calendar. I know well how to do it in main calendar so I only ask, how to change calendar_service to read and write to other calendar. I've tried loging with secondary ca...
How can I edit a secondary calendar using google python API
I wonder if it's possible to create and delete events with Google API in a secondary calendar. I know well how to do it in main calendar so I only ask, how to change calendar_service to read and write to other calendar. I've tried loging with secondary calendar email, but that's not possible with BadAuthentication Erro...
[ "A'm answering my own question so I can finally accept this one. The problem has been solved some time ago.\nThe most important answer is in this documentation.\nEach query can be run with uri as argument. For example \"InsertEvent(event, uri)\". Uri can be set manually (from google calendar settings) or automatica...
[ 1, 0 ]
[]
[]
[ "google_api", "google_calendar_api", "python" ]
stackoverflow_0004806237_google_api_google_calendar_api_python.txt
Q: SUDS loosing SOAP part of body I'm sending a SOAP request to update some entity. When I create (instead of update) nearly same thing, everything works fine. I've tracked logging from Client and Transport and finally it gave me a clue. It looks like this: DEBUG:suds.client:sending to (https://webservices.autotask.n...
SUDS loosing SOAP part of body
I'm sending a SOAP request to update some entity. When I create (instead of update) nearly same thing, everything works fine. I've tracked logging from Client and Transport and finally it gave me a clue. It looks like this: DEBUG:suds.client:sending to (https://webservices.autotask.net/ATServices/1.5/atws.asmx) message...
[ "I'm answering my own question, so I can finally close it.\nIf anyone will be interested, the problem was solved. There is a bug in suds.sx reported here. As the SOAP request was edited with this one, the request which I sent was empty. To correct it, I had to delete the sx part and change it with a MessagePlugin. ...
[ 1 ]
[]
[]
[ "python", "soap", "suds" ]
stackoverflow_0005714903_python_soap_suds.txt
Q: Python word count and rank Working on a word occurrence count application in a Python 3.2 / Windows environment. Can anyone please help to tell me why the following isn't working? from string import punctuation from operator import itemgetter N = 100 words = {} words_gen = (word.strip(punctuation).lower() for li...
Python word count and rank
Working on a word occurrence count application in a Python 3.2 / Windows environment. Can anyone please help to tell me why the following isn't working? from string import punctuation from operator import itemgetter N = 100 words = {} words_gen = (word.strip(punctuation).lower() for line in open("poi_run.txt") ...
[ "In Python 3, use just items where you'd previously use iteritems.\nThe new items() returns a dictionary view object that supports iteration as well as len and in.\nAnd of course, in top_words = (words.iteritems(), ... you forgot to call the sorted function.\n\nEdit: Please see my other answer for a better solution...
[ 4, 4, 2 ]
[]
[]
[ "python", "python_3.x" ]
stackoverflow_0007888786_python_python_3.x.txt
Q: python - mptt for nested lists I have read a little about mptt solution and I'm trying to implement some sort of translating a nested list into a mptt list. I know, that in this format it's useless, but nested lists can be easily changed with a classes childs or anything else. The code I have is: tree = [[1,[[11,[...
python - mptt for nested lists
I have read a little about mptt solution and I'm trying to implement some sort of translating a nested list into a mptt list. I know, that in this format it's useless, but nested lists can be easily changed with a classes childs or anything else. The code I have is: tree = [[1,[[11,[111, 112, 113]],[12,]]],[2,[[21,[[21...
[ "The problem has been solved by adding a global iterator.\nIf someone is interested, that's the new numerate function, which actually works fine.\nglobal_iterator = 0\n\ndef numerate(table, tree):\n global global_iterator\n for item in tree:\n global_iterator += 1\n\n\n if type(item) == type(1):...
[ 0 ]
[]
[]
[ "mptt", "python", "recursion" ]
stackoverflow_0006664199_mptt_python_recursion.txt
Q: Creating python script for HPQC: Setting filter properties I have created a python script to connect to HPQC and get the bugs. I am trying to limit the amount of bugs I get by setting the Filter from the BugFactory. This is proving difficult to do, the documentation says that I need to set the properties like so b...
Creating python script for HPQC: Setting filter properties
I have created a python script to connect to HPQC and get the bugs. I am trying to limit the amount of bugs I get by setting the Filter from the BugFactory. This is proving difficult to do, the documentation says that I need to set the properties like so bugFactory = td.BugFactory bugFilter = bugFactory.Filter bugFil...
[ "The call would be \nbugFilter.SetFilter('Field name', 'Setting')\n\n" ]
[ 2 ]
[]
[]
[ "python" ]
stackoverflow_0004135237_python.txt
Q: Draw graphs using Networkx to_agraph() I have a networkx digraph object. I can draw the graph in a file using to_agraph. But I want to draw the graph in memory, something that I can then save in a database table, without necessarily writing it to a file. Is there a way to do so? Following is the code that I use to...
Draw graphs using Networkx to_agraph()
I have a networkx digraph object. I can draw the graph in a file using to_agraph. But I want to draw the graph in memory, something that I can then save in a database table, without necessarily writing it to a file. Is there a way to do so? Following is the code that I use to draw my graph to a file. import networkx as...
[ "If you don't specify a file you will get a string with the image data.\ne.g.\nIn [1]: import networkx as nx\n\nIn [2]: G=nx.path_graph(4)\n\nIn [3]: A=nx.to_agraph(G)\n\nIn [4]: A.layout(prog='dot')\n\nIn [5]: png=A.draw(format='png')\n\nIn [6]: png[0:10]\nOut[6]: '\\x89PNG\\r\\n\\x1a\\n\\x00\\x00'\n\n" ]
[ 1 ]
[]
[]
[ "networkx", "python" ]
stackoverflow_0007881441_networkx_python.txt
Q: wxPython tree control does not expand to size of its containing panel I have a frame , and a panel attached to it : panel= wx.Panel(self, -1,style=wx.SIMPLE_BORDER) Then I make a tree control widget within this panel : tree = wx.TreeCtrl(panel, 1,style= wx.TR_HAS_BUTTONS) I add it to a vertical sizer : vbox1=wx....
wxPython tree control does not expand to size of its containing panel
I have a frame , and a panel attached to it : panel= wx.Panel(self, -1,style=wx.SIMPLE_BORDER) Then I make a tree control widget within this panel : tree = wx.TreeCtrl(panel, 1,style= wx.TR_HAS_BUTTONS) I add it to a vertical sizer : vbox1=wx.BoxSizer(wx.VERTICAL) vbox1.Add(panel, 1, wx.EXPAND | wx.ALL, 3) but when...
[ "Add the tree control to a sizer that is within the panel with similar parameters:\ntreeSizer = wx.BoxSizer(wx.VERTICAL)\ntreeSizer.Add(tree, 1, wx.EXPAND)\npanel.SetSizer(treeSizer)\n\n" ]
[ 2 ]
[]
[]
[ "python", "wxpython" ]
stackoverflow_0007888606_python_wxpython.txt
Q: Missing OAuth request token cookie error using tornado and TwitterMixin I'm using tornado and the TwitterMixin and I use the following basic code: class OauthTwitterHandler(BaseHandler, tornado.auth.TwitterMixin): @tornado.web.asynchronous def get(self): if self.get_argument("oauth_token", None)...
Missing OAuth request token cookie error using tornado and TwitterMixin
I'm using tornado and the TwitterMixin and I use the following basic code: class OauthTwitterHandler(BaseHandler, tornado.auth.TwitterMixin): @tornado.web.asynchronous def get(self): if self.get_argument("oauth_token", None): self.get_authenticated_user(self.async_callback(self._on_auth)...
[ "Two reasons why this might happen:\n\nSome users may have cookies turned off, in which case this won't work.\nThe cookie hasn't authenticated. It's possible that the oauth_token argument is set, but the cookie is not. Not sure why this would happen, you'd have to log some logging to understand why.\n\nAt any rate,...
[ 1, 1, 0 ]
[]
[]
[ "cookies", "oauth", "python", "tornado", "twitter" ]
stackoverflow_0006774563_cookies_oauth_python_tornado_twitter.txt
Q: split objects in a list separated by ',' in python I have a list of elements. for each element I want to split into 3 numbers separated by ',' and print them. My code is not doing what I want. :S l = ['14,23,63\n','41,20,76\n','65,23,42\n'] for element in l: element.split(',') print element[0],element[1],...
split objects in a list separated by ',' in python
I have a list of elements. for each element I want to split into 3 numbers separated by ',' and print them. My code is not doing what I want. :S l = ['14,23,63\n','41,20,76\n','65,23,42\n'] for element in l: element.split(',') print element[0],element[1],element[2] #outcome should be e.g. 14,23,63
[ "str.split returns a new list.\nfor element in l:\n parts = element.split(',')\n print parts\n\nAlso you probably want to trim as well (element.strip().split(',')).\n", "print [map(int, x.split(\",\")) for x in l]\n\nprints\n[[14, 23, 63], [41, 20, 76], [65, 23, 42]]\n\nThis not only splits the strings, it ...
[ 9, 3, 2 ]
[]
[]
[ "python" ]
stackoverflow_0007890087_python.txt
Q: Condensing output with python and multiprocessing so I've been writing numerical stuff with numpy and multiprocessing for some time now. It works ok, but I'm having trouble collecting the results. I've done it in the following way, I take a queue for input and one for output. The program reads the parameters from ...
Condensing output with python and multiprocessing
so I've been writing numerical stuff with numpy and multiprocessing for some time now. It works ok, but I'm having trouble collecting the results. I've done it in the following way, I take a queue for input and one for output. The program reads the parameters from the input queue, processes it and then puts the result ...
[ "Thats because you have block=False. When the collector tries to get data from the queue, it doesn't find it there immediately. So Empty exception is raised and it breaks out of the loop\nWhile getting data from the input list, you can specify block=False as its a prepopulated list, I assume. However, the output qu...
[ 2, 2 ]
[]
[]
[ "multicore", "multiprocessing", "numpy", "pickle", "python" ]
stackoverflow_0007890306_multicore_multiprocessing_numpy_pickle_python.txt
Q: Trigger in sqlachemy I have two tables related via a foreign key, here they are using Declarative Mapping class Task(DeclarativeBase): __tablename__ = 'task' id = Column(Integer, primary_key=True) state = Column(Integer, default=0) obs_id = Column(Integer, ForeignKey('obs.id'), nullable=False) cla...
Trigger in sqlachemy
I have two tables related via a foreign key, here they are using Declarative Mapping class Task(DeclarativeBase): __tablename__ = 'task' id = Column(Integer, primary_key=True) state = Column(Integer, default=0) obs_id = Column(Integer, ForeignKey('obs.id'), nullable=False) class Obs(DeclarativeBase): ...
[ "You can create trigger in the database with DDL class:\nupdate_task_state = DDL('''\\\nCREATE TRIGGER update_task_state UPDATE OF state ON obs\n BEGIN\n UPDATE task SET state = 2 WHERE (obs_id = old.id) and (new.state = 2);\n END;''')\nevent.listen(Obs.__table__, 'after_create', update_task_state)\n\nThis is ...
[ 37 ]
[]
[]
[ "python", "sqlalchemy", "triggers" ]
stackoverflow_0007888846_python_sqlalchemy_triggers.txt
Q: exporting from/importing to numpy, scipy in SQLite and HDF5 formats There seems to be many choices for Python to interface with SQLite (sqlite3, atpy) and HDF5 (h5py, pyTables) -- I wonder if anyone has experience using these together with numpy arrays or data tables (structured/record arrays), and which of these ...
exporting from/importing to numpy, scipy in SQLite and HDF5 formats
There seems to be many choices for Python to interface with SQLite (sqlite3, atpy) and HDF5 (h5py, pyTables) -- I wonder if anyone has experience using these together with numpy arrays or data tables (structured/record arrays), and which of these most seamlessly integrate with "scientific" modules (numpy, scipy) for ea...
[ "Most of it depends on your use case. \nI have a lot more experience dealing with the various HDF5-based methods than traditional relational databases, so I can't comment too much on SQLite libraries for python...\nAt least as far as h5py vs pyTables, they both offer very seamless access via numpy arrays, but they'...
[ 23 ]
[]
[]
[ "hdf5", "numpy", "python", "scipy", "sqlite" ]
stackoverflow_0007883646_hdf5_numpy_python_scipy_sqlite.txt
Q: Remove duplicate keys from a dictionary list I am new to Python, and I am currently stumped by this problem: I have a list of dictionaries generated csv.DictReader. I have created the list with the function as follows: def csvToDictList(filename): reader = csv.DictReader(open(filename, 'rb')) list = [] ...
Remove duplicate keys from a dictionary list
I am new to Python, and I am currently stumped by this problem: I have a list of dictionaries generated csv.DictReader. I have created the list with the function as follows: def csvToDictList(filename): reader = csv.DictReader(open(filename, 'rb')) list = [] for row in reader: list.append(row) ...
[ "There is nothing like duplicate keys in a dictionary.\nIf you have more columns with the same name, DictReader will take only the last one (overwriting the previous ones).\nFor the following CSV file:\na,b,c,a,b\n1,2,3,4,5\n6,7,8,9,10\n\nthe DictReader will return following dicts:\n{'a': '4', 'c': '3', 'b': '5'}\n...
[ 2 ]
[]
[]
[ "dictionary", "duplicate_removal", "list", "python" ]
stackoverflow_0007891201_dictionary_duplicate_removal_list_python.txt
Q: How to pass extra arguments to callback register functions with twisted python api? I have the following python code using the twisted API. def function(self,filename): def results(result): //do something for i in range(int(numbers)) : name = something that has to do with the value of i...
How to pass extra arguments to callback register functions with twisted python api?
I have the following python code using the twisted API. def function(self,filename): def results(result): //do something for i in range(int(numbers)) : name = something that has to do with the value of i df = function_which_returns_a defer(name) df.addCallback(result...
[ "You can pass extra arguments to a Deferred callback at the Deferred.addCallback call site by simply passing those arguments to Deferred.addCallback:\ndef function(self,filename): \n def results(result, name):\n # do something\n for i in range(int(numbers)) :\n name = something that has to do ...
[ 20 ]
[]
[]
[ "python", "twisted" ]
stackoverflow_0007891062_python_twisted.txt
Q: How can I create a model with compound foreign key? anybody knows on how to create a model with compound foreign key to another model. e.g. UserInfo: userId, password, key, ... GeoInfo: id, userId, password, storeName, ... In the above sample models. Want to link GeoInfo to UserInfo using two fields (userId, passw...
How can I create a model with compound foreign key?
anybody knows on how to create a model with compound foreign key to another model. e.g. UserInfo: userId, password, key, ... GeoInfo: id, userId, password, storeName, ... In the above sample models. Want to link GeoInfo to UserInfo using two fields (userId, password). note:I know how to link two models with one foreign...
[ "What's keeping you from having two ForeignKey field referencing Model A?\ne.g.\nclass Author(models.Model):\n name = models.CharField(max_length=50)\n\nclass Book(models.Model):\n title = models.CharField(max_length=50)\n author = models.ForeignKey(Author, related_name=\"primary_authors\")\n co_author ...
[ 0 ]
[]
[]
[ "compound_key", "django_models", "geodjango", "postgis", "python" ]
stackoverflow_0007873722_compound_key_django_models_geodjango_postgis_python.txt
Q: django's DateField model field and acceptable values I'm having a bit of trouble with django's DateField model field. Shouldn't it be able to accept fiveDaysLater as a valid date object? When I try to add fiveDaysLater into the database, I get an error saying cannot add null value to date. However, the second I...
django's DateField model field and acceptable values
I'm having a bit of trouble with django's DateField model field. Shouldn't it be able to accept fiveDaysLater as a valid date object? When I try to add fiveDaysLater into the database, I get an error saying cannot add null value to date. However, the second I change the date field to a regular CharField, the fiveDay...
[ "\"However, the second I change the date field to a regular CharField...\" Just a suspicion but if you made this change in your code, make sure to delete and recreated the Speech table using syncdb, otherwise, sqlite will not be aware of this change. (or you could change the datatype using sqlite exporer for firefo...
[ 0 ]
[]
[]
[ "django", "django_models", "django_views", "python" ]
stackoverflow_0007536421_django_django_models_django_views_python.txt
Q: Obtain an aware datetime object out of a string Is there a way I can obtain a datetime aware object out of a string in Python using only the standard library modules ? I know that I can use dateutil.parser.parse, but unfortunately that's not a good enough reason to add it as a dependency to my project. I already h...
Obtain an aware datetime object out of a string
Is there a way I can obtain a datetime aware object out of a string in Python using only the standard library modules ? I know that I can use dateutil.parser.parse, but unfortunately that's not a good enough reason to add it as a dependency to my project. I already have the mx.DateTime module as a dependency, buuttttt:...
[ "mx.DateTime.ISO.ParseDateTimeUTC is doing the right thing - it is applying the specified timezone to adjust the time to UTC. The resulting UTC time doesn't have a timezone because it isn't a local time anymore.\nThe standard Python library doesn't contain any concrete timezone classes according to the documentatio...
[ 2 ]
[]
[]
[ "datetime", "python" ]
stackoverflow_0007891300_datetime_python.txt
Q: Deploying Django on an apache server I am new to web development. So be gentle. AND thanks in advance. I am developing on windows env. and deploying on a linux server w/ Python 2.6.2 installed. Running apache2.2 as Virtual Host, and I am using mod_wsgi. I plan to serve media files from the same Virtual Host. I hav...
Deploying Django on an apache server
I am new to web development. So be gentle. AND thanks in advance. I am developing on windows env. and deploying on a linux server w/ Python 2.6.2 installed. Running apache2.2 as Virtual Host, and I am using mod_wsgi. I plan to serve media files from the same Virtual Host. I have a django site and I am now ready to depl...
[ "\nIt doesn't matter where the files go. They just have to be readable/executable by the user that the web server is running under.\nI don't know what you mean by django.wsgi~, that sounds like a backup file created by your editor - you don't need that.\nYes the httpd.conf is the configuration file for Apache. Some...
[ 3, 3, 1, 1 ]
[]
[]
[ "deployment", "django", "mod_wsgi", "python" ]
stackoverflow_0007878614_deployment_django_mod_wsgi_python.txt
Q: Serial Ports Context Manager Is the following a reasonable approach? with SerialPorts() as serial_ports: in= SerialPort("COM1") serial_ports.add(in) out = SerialPort("COM2") serial_ports.add(out) # use in and out where SerialPorts and SerialPort implement the context manager interface. Serial...
Serial Ports Context Manager
Is the following a reasonable approach? with SerialPorts() as serial_ports: in= SerialPort("COM1") serial_ports.add(in) out = SerialPort("COM2") serial_ports.add(out) # use in and out where SerialPorts and SerialPort implement the context manager interface. SerialPorts.exit() loops through the add...
[ "How about this?\nwith SerialPorts(\"COM1\", \"COM2\") as (inport, outport):\n # use inport and outport\n\nin is a reserved word in python, and using it as a variable name will result in a SyntaxError. \n\nEdit: Here's one possible implementation (untested):\nimport serial\nfrom contextlib import contextmanager ...
[ 2, 2 ]
[]
[]
[ "contextmanager", "python" ]
stackoverflow_0007891746_contextmanager_python.txt
Q: while redirecting to a view this error happens:invalid literal for int() with base 10 in urls.py : (r'^airAgency/(?P<key>[a-zA-Z0-9]+)/edittour/(?P<tour_id>\d+)/$','airAgency.views.edittour'), in views.py : tour.save() ang=Agent.objects.get(pk=key) return HttpResponseRedirect('airAgency/%s/edittour/%i/edit...
while redirecting to a view this error happens:invalid literal for int() with base 10
in urls.py : (r'^airAgency/(?P<key>[a-zA-Z0-9]+)/edittour/(?P<tour_id>\d+)/$','airAgency.views.edittour'), in views.py : tour.save() ang=Agent.objects.get(pk=key) return HttpResponseRedirect('airAgency/%s/edittour/%i/edittour.html' % (agn.WebSite,tour.pk)) note: tour is a form,after saving form tour pk is used...
[ "The value of tour.pk can't be converted to an integer by the %i format specifier.\nIt needs to be a string containing an integer (with or without a sign, ignores leading zeros), a numeric type like float, or a class with an __int__ method.\n", "As agf said, you can get around your problem by simply replacing thi...
[ 3, 1, 1 ]
[]
[]
[ "django", "python" ]
stackoverflow_0007889532_django_python.txt
Q: Accessing self from a ctype callback function in Python? I want to be able to call self from inside the callback function. class MyClass(): def myMethod(self): def myCallback(p1): print "Callback called!" # here I want to do something with self! CALLBACK_x = ctypes.WINF...
Accessing self from a ctype callback function in Python?
I want to be able to call self from inside the callback function. class MyClass(): def myMethod(self): def myCallback(p1): print "Callback called!" # here I want to do something with self! CALLBACK_x = ctypes.WINFUNCTYPE(ctypes.c_void_p, ctypes.c_uint32) somedll.setC...
[ "self should already be available in myCallback. Since it's created inside a function, it has access to the enclosing function's variables, including self. These variables are actually stored with the inner function in what's called a closure, so they stick around even after the enclosing function returns. Here's a...
[ 3, 0, 0 ]
[]
[]
[ "callback", "ctypes", "python" ]
stackoverflow_0007891585_callback_ctypes_python.txt
Q: my login view doesn't work in views.py : def login(request): if 'username' in request.POST and 'password' in request.POST: user=User.objects.get(Username__exact=request.POST['username'],Password__exact=request.POST['password']) request.session['username']=user.Username request.session['lastlog...
my login view doesn't work
in views.py : def login(request): if 'username' in request.POST and 'password' in request.POST: user=User.objects.get(Username__exact=request.POST['username'],Password__exact=request.POST['password']) request.session['username']=user.Username request.session['lastlogin']=user.Lastlogin return...
[ "DO NOT USE THIS.\nYou have created your own user model, and appear to be storing passwords in plain text. This is very dangerous. Do not do it.\nDjango has a built-in user authentication framework, fully documented here, which properly hashes passwords for security, and includes login forms. Use that instead. Even...
[ 7, 1, 1 ]
[]
[]
[ "django", "python" ]
stackoverflow_0007892162_django_python.txt
Q: python datetime now without daylight savings I'm lost in the tzinfo documentation. I want to create a datetime object for my location which does not include an adjustment for daylight savings. At the moment I am ugly hacking it: import time import datetime now=datetime.datetime.now() if time.localtime().tm_isdst==...
python datetime now without daylight savings
I'm lost in the tzinfo documentation. I want to create a datetime object for my location which does not include an adjustment for daylight savings. At the moment I am ugly hacking it: import time import datetime now=datetime.datetime.now() if time.localtime().tm_isdst==1: now=now+datetime.timedelta(hours=-1) What'...
[ "If you really want to create a \"bogus\" time by removing the effect of DST, your current solution will work.\nHowever, the best practice for working with dates is representing all dates as UTC internally, and only deal with timezone differences for user interaction. This way you don't have to care about all the ...
[ 6 ]
[]
[]
[ "datetime", "python" ]
stackoverflow_0007890823_datetime_python.txt
Q: Defining a global object in web service This is about my solution to that question It is been a long time since my last c# coding, and it is my first time to write a Web Service... Previous Question: I need to use a DLL on an Ubuntu with Python. Final solution is using a web service for that propose... My proble...
Defining a global object in web service
This is about my solution to that question It is been a long time since my last c# coding, and it is my first time to write a Web Service... Previous Question: I need to use a DLL on an Ubuntu with Python. Final solution is using a web service for that propose... My problem is, the API is used for a kind of payment. ...
[ "If you're communicating using a web service, it should preferrably be stateless – that is, you should always send any context information the service implementation needs in the request. While technologies that let you implement stateful web services exist, they'd likely make things more complicated, not less.\nI'...
[ 1 ]
[]
[]
[ "c#", "python", "web_services" ]
stackoverflow_0007892326_c#_python_web_services.txt
Q: Trying to print a single string on multiple lines of fixed length and minimizing the cost First some background I just started with Algorithms(which I now feel I lack the logic and reasoning power to excel at)I have been trying to print "This is a sample text "into various lines with max of 7 chars on each line so...
Trying to print a single string on multiple lines of fixed length and minimizing the cost
First some background I just started with Algorithms(which I now feel I lack the logic and reasoning power to excel at)I have been trying to print "This is a sample text "into various lines with max of 7 chars on each line so the first line will have : this is (no spaces left in the end so cost 0) a [cost=6*6*6(The ...
[ "Once approach is to list all possible alternatives and pick the one with the minimum cost:\nfrom functools import wraps\n\ndef cache(origfunc):\n d = {}\n @wraps(origfunc)\n def wrapper(*args):\n if args in d:\n return d[args]\n result = origfunc(*args)\n d[args] = result\n...
[ 2, 2, 0 ]
[]
[]
[ "algorithm", "python" ]
stackoverflow_0007860461_algorithm_python.txt
Q: error in matplotlib library in python while using csv2rec I am working in Ipython, trying to load a csv file. from matplotlib import * data=matplotlib.mlab.csv2rec('helix.csv',delimiter='\t') Here is the error message IOError Traceback (most recent call last) /mnt/hgfs/docs/pytho...
error in matplotlib library in python while using csv2rec
I am working in Ipython, trying to load a csv file. from matplotlib import * data=matplotlib.mlab.csv2rec('helix.csv',delimiter='\t') Here is the error message IOError Traceback (most recent call last) /mnt/hgfs/docs/python/<ipython console> in <module>() /usr/lib/pymodules/python2.7/...
[ "I tried with this file:\nsnp1,snp2,snp3\nA,A,A\nA,B,A\nB,B,B\n\nand here is the result:\nIn [3]: csv2rec('helix.csv')\nOut[3]: \nrec.array([('A', 'A', 'A'), ('A', 'B', 'A'), ('B', 'B', 'B')], \n dtype=[('snp1', '|S1'), ('snp2', '|S1'), ('snp3', '|S1')])\n\nI have matplotlib 1.0.1, so you might try updating it...
[ 1 ]
[]
[]
[ "csv", "ipython", "matplotlib", "numpy", "python" ]
stackoverflow_0007532270_csv_ipython_matplotlib_numpy_python.txt
Q: subtree with networkX In networkX, I have a tree as DiGraph(). #!/usr/bin/python # -*- coding: utf-8 -*- import networkx as nx t = nx.DiGraph() t.add_edge(1,'r') t.add_edge(2,'r') t.add_edge(3,'r') t.add_edge(4,2) t.add_edge(5,2) t.add_edge(6,5) print t.edges() If a take the node 2 of tree. how I can get the sub...
subtree with networkX
In networkX, I have a tree as DiGraph(). #!/usr/bin/python # -*- coding: utf-8 -*- import networkx as nx t = nx.DiGraph() t.add_edge(1,'r') t.add_edge(2,'r') t.add_edge(3,'r') t.add_edge(4,2) t.add_edge(5,2) t.add_edge(6,5) print t.edges() If a take the node 2 of tree. how I can get the subtree of 2 ? Edit I expected...
[ "If you mean the subtree rooted at node 2, that's\nfrom networkx.algorithms.traversal.depth_first_search import dfs_tree\n\nsubtree_at_2 = dfs_tree(t, 2)\n\nEdit: it seems you've reversed the order of nodes in your edges. In a directed tree, all paths proceed from the root to a leaf, not the other way around. dfs_t...
[ 12 ]
[]
[]
[ "networkx", "python", "subtree", "tree" ]
stackoverflow_0007892144_networkx_python_subtree_tree.txt
Q: subscripting with 2 arguments in python Assume I have a class X which has 2 attributes : i and j. I want to have : x = X((1,2,3),(2,3,4)) #this would set i to (1,2,3) and j to (2,3,4) I now want subscripting to work in the following way : a, b = x[1,2] #a should now be 2 and b should now be 3 At the moment I'm t...
subscripting with 2 arguments in python
Assume I have a class X which has 2 attributes : i and j. I want to have : x = X((1,2,3),(2,3,4)) #this would set i to (1,2,3) and j to (2,3,4) I now want subscripting to work in the following way : a, b = x[1,2] #a should now be 2 and b should now be 3 At the moment I'm trying this : def __getitem__(self, i, j):...
[ "Comma is the tuple packing operator. x[1, 2] calls x.__getitem__((1, 2)).\ndef __getitem__(self, ij):\n i, j = ij\n return self.x[i], self.y[j]\n\n" ]
[ 7 ]
[]
[]
[ "python", "subscript_operator" ]
stackoverflow_0007893557_python_subscript_operator.txt
Q: Python/wxPython Black Box Glitch Perhaps this is best asked on the wxPython mailing list, but I thought I'd ask here first to see if it is a known issue (I couldn't find anything about it via google). If my computer has been on for awhile (Windows), then my wxPython applications will often be displayed weird, with...
Python/wxPython Black Box Glitch
Perhaps this is best asked on the wxPython mailing list, but I thought I'd ask here first to see if it is a known issue (I couldn't find anything about it via google). If my computer has been on for awhile (Windows), then my wxPython applications will often be displayed weird, with black boxes over many widgets and my ...
[ "I got a new computer and the specs are slightly different:\n\nPython 2.5.2 (32bit install)\nwxPython 2.9.1.1 (32bit install)\n64bit Windows XP\n3.5GB RAM\nNvidia Quadro 4000\n\nI believe the \"black box\" issues was a problem with the wxPython implementation on Windows. I don't get the black box errors anymore (w...
[ 0 ]
[]
[]
[ "python", "visual_glitch", "wxpython" ]
stackoverflow_0006755516_python_visual_glitch_wxpython.txt
Q: Django: How to avoid duplicated html id for showing field twice in the same form? I want to generate the same field twice in the same form, which is useful when there are condition to show 1st textInput or 2nd textInput: Django will generate: <!--same form --> <input type="radio" value="good_price"/> <!-- show goo...
Django: How to avoid duplicated html id for showing field twice in the same form?
I want to generate the same field twice in the same form, which is useful when there are condition to show 1st textInput or 2nd textInput: Django will generate: <!--same form --> <input type="radio" value="good_price"/> <!-- show good price if this is checked --> <input type="radio" value="bad_price"/> <!-- show bad pr...
[ "If you are using \n{{ form.element }}\nYou can do the following:\n{{ form.element|attr:\"id:another_name\" }}\n\nSorry didn't realized the template filter i used:\nhttp://djangosnippets.org/snippets/729/\nI just changed = by :\n" ]
[ 1 ]
[]
[]
[ "django", "python" ]
stackoverflow_0007892558_django_python.txt
Q: Errors detected when loading a vim plugin from .vimrc I have installed vim 7.3 on debian system along with some vimrc i have downloaded from internet. It used to work fine on my other debian machine but here i get these error messages while i load the vim editor. Here are the errors: Error detected while processi...
Errors detected when loading a vim plugin from .vimrc
I have installed vim 7.3 on debian system along with some vimrc i have downloaded from internet. It used to work fine on my other debian machine but here i get these error messages while i load the vim editor. Here are the errors: Error detected while processing /home/tejinder/.vim/plugin/gundo.vim: line 196: E319: S...
[ "On debian install vim-gnome or vim-nox if you dont have X-server on system.\n$ sudo apt-get install vim-nox\n\nThese versions include python support for vim.\n", "The first error message is the one to look at: \"python\" isn't available in your vim. You may have \"vim-tiny\" installed. Try \"apt-get install vi...
[ 6, 4, 3, 0, 0 ]
[]
[]
[ "editor", "python", "vi", "vim" ]
stackoverflow_0004574933_editor_python_vi_vim.txt
Q: Trying to turn inner and out tuples into inner and outer lists Ok, so I've got information in the form of (('A', 'B', 'C'), ('D', 'E', 'F'), ('H', 'I', 'J')) and I would like to convert this to [['A', 'B', 'C'], ['D', 'E', 'F'], ['H', 'I', 'J']] What is the best/easiest way to do this? A: List comprehension: t...
Trying to turn inner and out tuples into inner and outer lists
Ok, so I've got information in the form of (('A', 'B', 'C'), ('D', 'E', 'F'), ('H', 'I', 'J')) and I would like to convert this to [['A', 'B', 'C'], ['D', 'E', 'F'], ['H', 'I', 'J']] What is the best/easiest way to do this?
[ "List comprehension:\ntpl = (('A', 'B', 'C'), ('D', 'E', 'F'), ('H', 'I', 'J'))\n\nlst = [list(x) for x in tpl]\n\n", "a = (('A', 'B', 'C'), ('D', 'E', 'F'), ('H', 'I', 'J'))\nprint map(list, a)\n\nprints\n[['A', 'B', 'C'], ['D', 'E', 'F'], ['H', 'I', 'J']]\n\n", ">>> data = (('A', 'B', 'C'), ('D', 'E', 'F'), (...
[ 5, 4, 3, 2, 2 ]
[]
[]
[ "arrays", "list", "python", "tuples" ]
stackoverflow_0007893848_arrays_list_python_tuples.txt
Q: Getting error in python script "AttributeError: 'module' object has no attribute 'auth_none' " I am writing python script to login to ssh server using paramiko. I wrote script below. #!/usr/bin/python import paramiko ssh = paramiko.SSHClient() ssh.set_missing_host_key_policy(paramiko.AutoAddPolicy()) paramiko.tra...
Getting error in python script "AttributeError: 'module' object has no attribute 'auth_none' "
I am writing python script to login to ssh server using paramiko. I wrote script below. #!/usr/bin/python import paramiko ssh = paramiko.SSHClient() ssh.set_missing_host_key_policy(paramiko.AutoAddPolicy()) paramiko.transport.auth_none('sachin') ssh.connect('localhost', username='sachin', password='abc123') stdin, std...
[ "The paramiko.transport module does not contain a name auth_none, as can be seen from its documentation (and from the error message as well).\nMaybe you want\nssh.get_transport().auth_none('sachin')\n\n", "auth_none must be called on a specific Transport instance, not on the transport module.\nSince the SSHClient...
[ 2, 2 ]
[]
[]
[ "paramiko", "python" ]
stackoverflow_0007894014_paramiko_python.txt
Q: Add a string to string values of an inner list Ok, so I have this list, [['A', 'B', 'C'], ['D', 'E', 'F'], ['G', 'H', 'I']] I want to add html tags to the values in the inner lists. How would I go about doing this? i.e. [['<b>A</b>', '<b>B</b>', '<b>C</b>'], ['<b>D</b>', '<b>E</b>', '<b>F</b>'], ['<b>G</b>', '<b...
Add a string to string values of an inner list
Ok, so I have this list, [['A', 'B', 'C'], ['D', 'E', 'F'], ['G', 'H', 'I']] I want to add html tags to the values in the inner lists. How would I go about doing this? i.e. [['<b>A</b>', '<b>B</b>', '<b>C</b>'], ['<b>D</b>', '<b>E</b>', '<b>F</b>'], ['<b>G</b>', '<b>H</b>', '<b>I</b>']]
[ "[['<b>%s</b>' % x for x in data] for data in my_list]\n\n", "Like this?\ndef AddHtml(s): return '<b>' + s + '</b>'\n\ndef AddHtmlArray(a) : return map(AddHtml, a)\n\n...\n\nmap(AddHtmlArray, yourList)\n\n", ">>> l = [['A', 'B', 'C'], ['D', 'E', 'F'], ['G', 'H', 'I']]\n\n>>> out = [['<b>'+s+'</b>' for s in subl...
[ 5, 1, 1 ]
[]
[]
[ "html", "list", "python" ]
stackoverflow_0007894043_html_list_python.txt
Q: How to get TEXTAREA value in a python server? I'm coding a simple python server to hold logs throughout a company. The site presents change logs for upcoming projects for all teams. Each team has the option to edit their logs. The way I did this was by making a form with a TEXTAREA which they fill out and submit. ...
How to get TEXTAREA value in a python server?
I'm coding a simple python server to hold logs throughout a company. The site presents change logs for upcoming projects for all teams. Each team has the option to edit their logs. The way I did this was by making a form with a TEXTAREA which they fill out and submit. However, I can't for the life of me figure out how ...
[ "I'm guessing that when you're getting the radio/checkbox/textbox values you're using a GET request, in which case the values will be sent as URL parameters. i.e.: \nyoururl.com/bla.html?radioName=someValue&bla=hi\nwhich you're using to retrieve the values. This is not the case with the POST request. As far as I kn...
[ 0 ]
[]
[]
[ "python", "textarea" ]
stackoverflow_0007893928_python_textarea.txt
Q: Python list elements removal logical error? Possible Duplicate: Removing from a list while iterating over it I have this code: s = [2,3,4,5] for i in s: s.remove(i) print(s) When I run it, the result is: [3,5] What is the logical error here ? A: You are iterating over the list while modifying it, which ...
Python list elements removal logical error?
Possible Duplicate: Removing from a list while iterating over it I have this code: s = [2,3,4,5] for i in s: s.remove(i) print(s) When I run it, the result is: [3,5] What is the logical error here ?
[ "You are iterating over the list while modifying it, which is causing your problem.\nMake a temporary list (list(s)) that you iterate over and modify the original to your needs:\n>>> s = [2,3,4,5]\n>>>\n>>> for i in list(s):\n... s.remove(i)\n... \n>>> print(s)\n[]\n\n", "The logical error is in removing elemen...
[ 2, 0, 0 ]
[]
[]
[ "python", "python_3.x" ]
stackoverflow_0007894161_python_python_3.x.txt
Q: Using url_for triggers AttributeError: 'thread._local' object has no attribute 'mapper' I am attempting to use url_for inside of a mako template with pyramid (using a book example): ${h.url_for(controller='formtest',action='submit')} When I do, I get this error: AttributeError: 'thread._local' object has no attri...
Using url_for triggers AttributeError: 'thread._local' object has no attribute 'mapper'
I am attempting to use url_for inside of a mako template with pyramid (using a book example): ${h.url_for(controller='formtest',action='submit')} When I do, I get this error: AttributeError: 'thread._local' object has no attribute 'mapper' I installed routes and put this in my helpers.py file: import webhelpers.html...
[ "Are you sure you're using Pyramid? Every thing that you have posted is about Pylons and not Pyramid. They are very different frameworks.\nAssuming you are using Pylons, url_for was deprecated. You should instead be using the url global variable which is imported from from pylons import url.\n" ]
[ 2 ]
[]
[]
[ "pyramid", "python", "routes", "url_for" ]
stackoverflow_0007894180_pyramid_python_routes_url_for.txt
Q: How is split('\n') method in Python implemented? This is a theoretical question to be able to understand a difference between Java and Python. To read the content of a file into an array in Java, you need to know the number of lines, in order to define the size of the array when you declare it. And because you can...
How is split('\n') method in Python implemented?
This is a theoretical question to be able to understand a difference between Java and Python. To read the content of a file into an array in Java, you need to know the number of lines, in order to define the size of the array when you declare it. And because you cannot know it in advance, you need to apply some tricks ...
[ "The implementation of str.split() internally calls list.append(), which in turn calls the internal function list_resize(). From a comment in the source code of this function:\n\nThis over-allocates proportional to the list size, making room\n for additional growth. The over-allocation is mild, but is\n enough ...
[ 10, 1, 0, 0, 0 ]
[]
[]
[ "python", "split" ]
stackoverflow_0005667359_python_split.txt
Q: How to loop through files and rename them in Python I have a directory of music that has album folders as well as individual songs on each level. How can I traverse all of these files that also are encoded in different formats(mp3, wav etc)? In addition is there a way I can rename them to a format that is more con...
How to loop through files and rename them in Python
I have a directory of music that has album folders as well as individual songs on each level. How can I traverse all of these files that also are encoded in different formats(mp3, wav etc)? In addition is there a way I can rename them to a format that is more consistent to my liking using regular expressions? Thanks
[ "\nos.walk to go over files in the directory and its sub-directories, recursively\nos.rename to rename them\n\nThe encoding of the files pays no role here, I think. You can, of course, detect their extension (use os.path.splitext for that) and do something based on it, but as long as you just need to rename files (...
[ 7, 1 ]
[]
[]
[ "directory_traversal", "filesystems", "python" ]
stackoverflow_0007894472_directory_traversal_filesystems_python.txt
Q: ImportError: No module named http.cookies error when installing cherrypy 3.2 I am having trouble installing cherrypy 3.2 on Linux machines (both on Ubuntu and Centos). I have the latest Python and Pip (version 2.7) installed on the machines. On Ubuntu, I am using $sudo pip install cherrypy. On centos, I was instal...
ImportError: No module named http.cookies error when installing cherrypy 3.2
I am having trouble installing cherrypy 3.2 on Linux machines (both on Ubuntu and Centos). I have the latest Python and Pip (version 2.7) installed on the machines. On Ubuntu, I am using $sudo pip install cherrypy. On centos, I was installing from source. After install finished and succeeded, when importing cherrypy mo...
[ "I ran into this today as well with a fresh install of python2.7.2 from source on centos5.6. I verified that running setup.py was using the correct subfolder (py2). In digging through _cpcompat.py it seems that it is assumed that you have SSL support, which I assumed myself. If you do not have SSL, then the followi...
[ 2, 1, 1 ]
[]
[]
[ "cherrypy", "python" ]
stackoverflow_0006643052_cherrypy_python.txt
Q: Search for a pattern in a lot of scramble letters (upper & lower cases) I have a lot of scrambled letters. In these letters i should find a pattern of XXXxXXX. Which means, three uppercase letters then one lowercase then another three uppercase. I am using Python to solve this problem, is there a way to do that ea...
Search for a pattern in a lot of scramble letters (upper & lower cases)
I have a lot of scrambled letters. In these letters i should find a pattern of XXXxXXX. Which means, three uppercase letters then one lowercase then another three uppercase. I am using Python to solve this problem, is there a way to do that easily? Also, I would like to print just the lowercase letters without the uppe...
[ "Using re:\n>>> a='alRfflkafdfaeGlkAYEuRFSbbvvcbF'\n>>> import re\n>>> r=re.compile(\"[A-Z]{3}[a-z][A-Z]{3}\")\n>>> r.findall(a)\n['AYEuRFS']\n\n" ]
[ 3 ]
[]
[]
[ "python" ]
stackoverflow_0007894288_python.txt
Q: How do I use the datetime module in IronPython? I am trying to port a program of mine from running on the CPython interpreter to IronPython. The latest part that stumps me is where I use the datetime class from the datetime module. Here is what happens when I try to use the strptime function. » from datetime impo...
How do I use the datetime module in IronPython?
I am trying to port a program of mine from running on the CPython interpreter to IronPython. The latest part that stumps me is where I use the datetime class from the datetime module. Here is what happens when I try to use the strptime function. » from datetime import datetime » dt = datetime.strptime("21/11/06 16:30"...
[ "For no particular reason, datetime.strptime was missing until IronPython 2.7.1. If you're stuck on an older version, you can use time.strptime instead.\n" ]
[ 2 ]
[]
[]
[ ".net", "datetime", "ironpython", "python" ]
stackoverflow_0007894261_.net_datetime_ironpython_python.txt
Q: error while accessing objects in ManyToMany relationship I have these 2 models: class Agency(models.Model): Location=models.ForeignKey(Location) Name=models.CharField(max_length=50) WebSite=models.CharField(max_length=100) class AgencyPosition(models.Model): Agency=models.ForeignKey(Agency) Users=m...
error while accessing objects in ManyToMany relationship
I have these 2 models: class Agency(models.Model): Location=models.ForeignKey(Location) Name=models.CharField(max_length=50) WebSite=models.CharField(max_length=100) class AgencyPosition(models.Model): Agency=models.ForeignKey(Agency) Users=models.ManyToManyField(User) PhoneNumber=models.CharField(ma...
[ "first off i think convention is to use lowercase with underscores for attributes in python classes, \nNext, when you use user.agencyposition_set.all()[:1] i think that returns a queryset object not an instance of the class you want, i think you might need just an instance to access its attributes.\nTo get a users ...
[ 1, 1 ]
[]
[]
[ "django", "python" ]
stackoverflow_0007894436_django_python.txt
Q: Django inline elements gives error for many-to-many relationship In the admin I want to use inline elements. I want category to display the items it is related to. But I get this error: Exception at /admin/store/category/7/ <class 'store.models.Item'> has no ForeignKey to <class 'store.models.Category'> It's true...
Django inline elements gives error for many-to-many relationship
In the admin I want to use inline elements. I want category to display the items it is related to. But I get this error: Exception at /admin/store/category/7/ <class 'store.models.Item'> has no ForeignKey to <class 'store.models.Category'> It's true, of-course, since I chose to use Category to point to the items it ha...
[ "The syntax is slightly different to display many-to-many relations using an inline. \nclass ItemInline(admin.TabularInline):\n model = Category.items.through\n\nclass CategoryAdmin(admin.ModelAdmin):\n inlines = [\n ItemInline,\n ]\n exclude = ('items',)\n\nSee the django admin docs for working ...
[ 1 ]
[]
[]
[ "django", "inline", "python" ]
stackoverflow_0007894963_django_inline_python.txt
Q: Look for an string inside a webpage without saving it in a file? I'm new with Python and I have some questions!! def extractdownloadurl(url): uresponse = urllib2.urlopen(url) #open url contents = uresponse.readlines() #readlines from url file fo = open("test.html","w") #open test.html for line in ...
Look for an string inside a webpage without saving it in a file?
I'm new with Python and I have some questions!! def extractdownloadurl(url): uresponse = urllib2.urlopen(url) #open url contents = uresponse.readlines() #readlines from url file fo = open("test.html","w") #open test.html for line in contents: fo.write(line)#write lines from url file to text fi...
[ "This should get you forward. This script prints all links from the web-page using your regular expression:\nimport re, urllib\npage = urllib.urlopen(\"http://sebsauvage.net/index.html\").read()\nurls = re.findall('href=[\\'\"]?([^\\'\" >]+)',page)\nfor url in urls:\n print url\n\n" ]
[ 1 ]
[]
[]
[ "python", "regex", "urllib2" ]
stackoverflow_0007895163_python_regex_urllib2.txt
Q: Javascript or Python: Newline after each sentence I'm curious if there's a library for python OR javascript to tokenize sentences of a string of sentences and put new line at each sentence? IE: Lorem ipsum dolor sit amet, consectetur adipiscing elit. Vestibulum aliquet leo in urna hendrerit placerat. Donec adipis...
Javascript or Python: Newline after each sentence
I'm curious if there's a library for python OR javascript to tokenize sentences of a string of sentences and put new line at each sentence? IE: Lorem ipsum dolor sit amet, consectetur adipiscing elit. Vestibulum aliquet leo in urna hendrerit placerat. Donec adipiscing dignissim adipiscing. Duis adipiscing mollis cursu...
[ "You are looking for a natural language library.\nFor Python there is Natural Language Toolkit (NLTK). For example you could take a look at the PunktSentenceTokenizer.\n\nThe PunktSentenceTokenizer divides a text into a list of sentences, by using an unsupervised algorithm to build a model for abbreviation words, c...
[ 4, 0, 0 ]
[]
[]
[ "javascript", "lexical", "python", "sentence" ]
stackoverflow_0007895312_javascript_lexical_python_sentence.txt
Q: sanity checks in python properties function partially I'm new to python and I would like some help. I created some classes with properties in order to keep me from passing meaningless arguments. So for example I have this class class match(object): __teams=(None,None) def setTeams(self,tms): i...
sanity checks in python properties function partially
I'm new to python and I would like some help. I created some classes with properties in order to keep me from passing meaningless arguments. So for example I have this class class match(object): __teams=(None,None) def setTeams(self,tms): if type(tms) != type(list()) and type(tms) != type(tuple()):...
[ "This error isn't because you are failing some typecheck.\nUnless you have misrepresented your code (it's obviously edited, as what you posted won't run correctly), this is happening because match1.teams[0] calls your getTeams function, not your setTeams function. To see this for yourself, try this exercise:\nclas...
[ 5, 4, 2 ]
[]
[]
[ "class", "properties", "python" ]
stackoverflow_0007894702_class_properties_python.txt
Q: Merging a list of lists How do I merge a list of lists? [['A', 'B', 'C'], ['D', 'E', 'F'], ['G', 'H', 'I']] into ['A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I'] Even better if I can add a value on the beginning and end of each item before merging the lists, like html tags. i.e., the end result would be: ['<tr>A</t...
Merging a list of lists
How do I merge a list of lists? [['A', 'B', 'C'], ['D', 'E', 'F'], ['G', 'H', 'I']] into ['A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I'] Even better if I can add a value on the beginning and end of each item before merging the lists, like html tags. i.e., the end result would be: ['<tr>A</tr>', '<tr>B</tr>', '<tr>C</tr...
[ "Don't use sum(), it is slow for joining lists.\nInstead a nested list comprehension will work:\n>>> x = [['A', 'B', 'C'], ['D', 'E', 'F'], ['G', 'H', 'I']]\n>>> [elem for sublist in x for elem in sublist]\n['A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I']\n>>> ['<tr>' + elem + '</tr>' for elem in _]\n\nThe advice to u...
[ 10, 3, 2, 0 ]
[]
[]
[ "list", "list_comprehension", "merge", "python", "python_itertools" ]
stackoverflow_0007895449_list_list_comprehension_merge_python_python_itertools.txt
Q: Decorating a model class in django issuing save in the decorator I have several models that save log data to my database. I also have a "recent events" app and I would like to choose which models send data to the events app. I thought a decorator would be good for this, so I could just add it to the models I want:...
Decorating a model class in django issuing save in the decorator
I have several models that save log data to my database. I also have a "recent events" app and I would like to choose which models send data to the events app. I thought a decorator would be good for this, so I could just add it to the models I want: @logger class TemperatureLog(models.Model): Date = models.DateTim...
[ "The \"in principle\" response to your question is to consider using the pre_save signal built into Django.\nBasically, you connect a listener function to the pre_save signal, documented in full at the link above, and you can modify the desired properties on your model instance. Only after your listener finishes ex...
[ 1, 0 ]
[]
[]
[ "decorator", "django", "django_models", "python" ]
stackoverflow_0007894526_decorator_django_django_models_python.txt
Q: Ensure that a list of URLs without a page part always ends with slash and dot I have a really big list of URLs and I'd like to add a slash and dot (/.) to all URLs that don't have a page part. Here are some examples of what I'd like to achieve: http://www.example.com should be http://www.example.com/. http://www....
Ensure that a list of URLs without a page part always ends with slash and dot
I have a really big list of URLs and I'd like to add a slash and dot (/.) to all URLs that don't have a page part. Here are some examples of what I'd like to achieve: http://www.example.com should be http://www.example.com/. http://www.example.com/index.htm is okay http://www.example.com/. is okay http://www.example...
[ "By \"page part\" you seem to mean something with '.htm' on the end (given your 2nd and 5th examples), so:\nurl = url.rstrip('/#.')\nif not url.endswith('.htm'):\n url += '/.'\n\n" ]
[ 0 ]
[]
[]
[ "python" ]
stackoverflow_0007895497_python.txt
Q: Delaying static class member initialization I have this (example) code: init() class A: foo = bar() def __init__(self): print(A.foo) The problem is, the function bar() refuses to work unless init() has been called first. What is a nice Pythonesque solution for this problem? In my specific situa...
Delaying static class member initialization
I have this (example) code: init() class A: foo = bar() def __init__(self): print(A.foo) The problem is, the function bar() refuses to work unless init() has been called first. What is a nice Pythonesque solution for this problem? In my specific situation init() is third-party and can not be adapted...
[ "Like this?\nclass A:\n foo = None\n def __init__(self):\n if A.foo is None:\n A.foo = bar()\n print(A.foo)\n\nYou could also move the if statement to A.__new__() if you are not sure A.__init__() will be called (e.g. when unpickling an A object before explicitly calling its construct...
[ 0, 0 ]
[]
[]
[ "initialization", "python", "static_members" ]
stackoverflow_0007895998_initialization_python_static_members.txt
Q: Integration issue with PyObjC and TKinter The following simple code: from PyObjCTools import AppHelper import AppKit import Tkinter class App(AppKit.NSApplication): def finishLaunching(self): self.root=Tkinter.Tk() _=App.sharedApplication() AppHelper.runEventLoop() yields the following exception: ...
Integration issue with PyObjC and TKinter
The following simple code: from PyObjCTools import AppHelper import AppKit import Tkinter class App(AppKit.NSApplication): def finishLaunching(self): self.root=Tkinter.Tk() _=App.sharedApplication() AppHelper.runEventLoop() yields the following exception: Python[23717:d07] -[App _setup:]: unrecognized ...
[ "I don't think you can mix Tkinter and Cocoa toolkits so interchangeably. self.root is an attribute on the class App, which inherits from AppKit.NSApplication. My guess is that the Tk() call returns a pointer that is then passed to the Cocoa frameworks, but points to a Tk data structure that it can't understand. Al...
[ 2 ]
[]
[]
[ "macos", "pyobjc", "python", "tkinter" ]
stackoverflow_0007042500_macos_pyobjc_python_tkinter.txt
Q: numpy: reorder array by specified values I have a matrix: A = [ [1,2], [3,4], [5,6] ] and a vector of values: V = [4,6,2] I would like to reorder A by 2nd column, using values from V. The result should be: A = [ [3,4], [5,6], [1,2] ] # 2nd columns' values have the same order as V How to...
numpy: reorder array by specified values
I have a matrix: A = [ [1,2], [3,4], [5,6] ] and a vector of values: V = [4,6,2] I would like to reorder A by 2nd column, using values from V. The result should be: A = [ [3,4], [5,6], [1,2] ] # 2nd columns' values have the same order as V How to do it?
[ "First, we need to find the indicies of the values in the second column of A that we'd need to match the order of V. In this case, that's [1,2,0]. Once we have those, we can just use numpy's \"fancy\" indexing to do the rest.\nSo, you might do something like this:\nimport numpy as np\nA = np.arange(6).reshape((3,...
[ 7, 6 ]
[]
[]
[ "numpy", "python" ]
stackoverflow_0007891247_numpy_python.txt
Q: What's wrong with this python program working on .csv? I have a text file with a list of strings. I want to search a .csv file for rows that begin with those strings and put them in a new .csv file. In this instance, the text file is called 'output.txt', the original .csv is 'input.csv' and the new .csv file is '...
What's wrong with this python program working on .csv?
I have a text file with a list of strings. I want to search a .csv file for rows that begin with those strings and put them in a new .csv file. In this instance, the text file is called 'output.txt', the original .csv is 'input.csv' and the new .csv file is 'corrected.csv'. The code: import csv file = open('output.tx...
[ "If you look at the documentation, this is how the reader is initialized:\nspamReader = csv.reader(open('eggs.csv', 'r'), ...\n\nNotice the open('eggs.csv, 'rb'). You aren't passing a file handle in line 9, so the str is being treated as a file handle and is throwing you the error.\nReplace line 9 with this:\ncsv.r...
[ 6, 2, 0 ]
[ "Try this\nimport csv\nimport cStringIO\n\nfile = open('output.txt') \nwhile True: \n line = file.readline()\n buf = cStringIO.StringIO() \n writer = csv.writer(buf, dialect = 'excel') \n for row in csv.reader(open('input.csv')): \n if not row[0].startswith(line): \...
[ -2 ]
[ "csv", "python" ]
stackoverflow_0007853606_csv_python.txt
Q: python file operation please, what is the meaning of this line: return [f[:f.rindex(".")] for f in os.listdir(path) if f and len(f) >= 4 and f[-2:] == "py" and f[-1] != "o" and f[-1] != "c"] I found it in a script in this link : http://www-users.cs.umn.edu/~mein/blender/plugins/python/misc/scriptloader/TheOneSc...
python file operation
please, what is the meaning of this line: return [f[:f.rindex(".")] for f in os.listdir(path) if f and len(f) >= 4 and f[-2:] == "py" and f[-1] != "o" and f[-1] != "c"] I found it in a script in this link : http://www-users.cs.umn.edu/~mein/blender/plugins/python/misc/scriptloader/TheOneScript.py I know that i neede...
[ "The length check is because the shortest sensible filename is a single character followed by .py, which gives at least 4 characters.\nThe last checks seem to be trying to ingore the compiled files with extensions .pyc and .pyo, but it's totally unnecessary as they won't match the condition f[-2:] == \"py\".\nFo...
[ 3, 2, 1, 0 ]
[]
[]
[ "file", "python" ]
stackoverflow_0007895929_file_python.txt
Q: Python profiling methods I would like to profile python code from an object point of view. E.g.: foo = Foo() profiled_foo = add_profiling(foo) # use profiled_foo like foo ... # later profiled_foo.print_profile() And I would like to get calls per method and cumulative time spent per method. I didn't find anythin...
Python profiling methods
I would like to profile python code from an object point of view. E.g.: foo = Foo() profiled_foo = add_profiling(foo) # use profiled_foo like foo ... # later profiled_foo.print_profile() And I would like to get calls per method and cumulative time spent per method. I didn't find anything similar, although I think it...
[ "I've had pretty good success with these decorators: http://mg.pov.lt/profilehooks/\n", "You can look at http://docs.python.org/library/profile.html\nIn my personal opinion cProfile is the more intuitive and quick profiling tools for python.\nTo profile single class you can write simple test script and run them w...
[ 6, 1, 1 ]
[]
[]
[ "profiling", "python" ]
stackoverflow_0007892469_profiling_python.txt
Q: python parse csv to lists I have a csv file thru which I want to parse the data to the lists. So I am using the python csv module to read that so basically the following: import csv fin = csv.reader(open(path,'rb'),delimiter=' ',quotechar='|') print fin[0] #gives the following ['"1239","2249.00","1","3","2011-02-2...
python parse csv to lists
I have a csv file thru which I want to parse the data to the lists. So I am using the python csv module to read that so basically the following: import csv fin = csv.reader(open(path,'rb'),delimiter=' ',quotechar='|') print fin[0] #gives the following ['"1239","2249.00","1","3","2011-02-20"'] #lets say i do the follow...
[ "Change your delimiter to ',' and you will get a list of those values from the csv reader.\n", "It's because you are converting a list to a string, there is no need to do this. Grab the first element of the list (in this case it is a string) and parse that:\n>>> a = ['\"1239\",\"2249.00\",\"1\",\"3\",\"2011-02-20...
[ 1, 0 ]
[]
[]
[ "csv", "python" ]
stackoverflow_0007896245_csv_python.txt
Q: sqlite3 python2.7 and Ubuntu 10.04 (or just python2.6) Question: How can I get my non-system Python2.7 to find the sqlite3 libraries? Details: I run Ubuntu 10.04 LTS which uses Python2.6. I have projects that require Python2.7. I use the --python=Python2.7 flags for virtualenv to have my project use that. I have...
sqlite3 python2.7 and Ubuntu 10.04 (or just python2.6)
Question: How can I get my non-system Python2.7 to find the sqlite3 libraries? Details: I run Ubuntu 10.04 LTS which uses Python2.6. I have projects that require Python2.7. I use the --python=Python2.7 flags for virtualenv to have my project use that. I have the following sqlite3 stuff installed libsqlite3-0 ...
[ "A recompile of python2.7 did the trick.\n" ]
[ 0 ]
[]
[]
[ "python", "sqlite", "ubuntu" ]
stackoverflow_0007826586_python_sqlite_ubuntu.txt
Q: multithreading/processing in Python Hello I am trying define values of a dictionary in parallel using multiprocessing. When the function f() is called outside "pool" the dictionary value is set correctly. In the pool call however it fails. What am I doing wrong? Thanks. from multiprocessing import Pool hits={...
multithreading/processing in Python
Hello I am trying define values of a dictionary in parallel using multiprocessing. When the function f() is called outside "pool" the dictionary value is set correctly. In the pool call however it fails. What am I doing wrong? Thanks. from multiprocessing import Pool hits={} def f(x): hits[x] = x #this will i...
[ "You spawn a bunch of subprocesses which inherit the current value of hits. Each subprocess get its own copy of hits and modifies it, then exits, dropping the process-local copy of hits.\nThe intended use of multiprocessing.Pool.map() is to use its return value, which you are ignoring. Each process could return i...
[ 7 ]
[]
[]
[ "multithreading", "python" ]
stackoverflow_0007896321_multithreading_python.txt
Q: appending to a 2D list in python where the row/col length is unknown I am looking to flip the rows and columns on a 2D list and am running into trouble. Python won't allow a value to be assigned to an uninitialized 'cell'. I am not sure how to initialize my grid since I don't know the length ahead of time. The ...
appending to a 2D list in python where the row/col length is unknown
I am looking to flip the rows and columns on a 2D list and am running into trouble. Python won't allow a value to be assigned to an uninitialized 'cell'. I am not sure how to initialize my grid since I don't know the length ahead of time. The following: data = list() maReader = csv.reader(open('TEST.csv', 'rb'), del...
[ "Here's an EAFP counterpoint to @retracile's LBYL approach.\ndata = [] #list()\nmaReader = csv.reader(open('TEST.csv', 'rb'), delimiter=',', quotechar='\"')\nfor rindex, row in enumerate(maReader):\n for iindex, item in enumerate(row):\n try:\n data[iindex].append(item)\n except IndexErr...
[ 3, 2, 2, 1 ]
[]
[]
[ "2d", "append", "grid", "list", "python" ]
stackoverflow_0007896008_2d_append_grid_list_python.txt
Q: Strange behavior of python's append? size = input('Kirjainmäärä: ') kirjaimet = "0ABCDEFGHIJKLMNOPQRSTUVWXYZ" ruudukko = [] rivi = ['0']*(size*2-1) for i in range(0,size): #produce n rows for y in range(0,i+1): #this row needs i+1 letters for z in range(0+i,size*2-1-i): rivi[z] = kirjaime...
Strange behavior of python's append?
size = input('Kirjainmäärä: ') kirjaimet = "0ABCDEFGHIJKLMNOPQRSTUVWXYZ" ruudukko = [] rivi = ['0']*(size*2-1) for i in range(0,size): #produce n rows for y in range(0,i+1): #this row needs i+1 letters for z in range(0+i,size*2-1-i): rivi[z] = kirjaimet[size-i] print rivi, i ruudukko.a...
[ "You aren't appending five different lists to your result. You are appending the same list five times.\nYou can fix it by appending a copy of your list to the result:\nruudukko.append(rivi[:])\n\nSee it working online: ideone\n", "list.append() stores a reference to the object appended. So you have stored multipl...
[ 2, 2, 0, 0 ]
[]
[]
[ "append", "python" ]
stackoverflow_0007896370_append_python.txt
Q: Why doesn't the operator module have a function for logical or? In Python 3, operator.or_ is equivalent to the bitwise |, not the logical or. Why is there no operator for the logical or? A: The or and and operators can't be expressed as functions because of their short-circuiting behavior: False and some_functio...
Why doesn't the operator module have a function for logical or?
In Python 3, operator.or_ is equivalent to the bitwise |, not the logical or. Why is there no operator for the logical or?
[ "The or and and operators can't be expressed as functions because of their short-circuiting behavior:\nFalse and some_function()\nTrue or some_function()\n\nin these cases, some_function() is never called.\nA hypothetical or_(True, some_function()), on the other hand, would have to call some_function(), because fun...
[ 22, 9, 2 ]
[]
[]
[ "bitwise_operators", "python", "python_3.x" ]
stackoverflow_0007894653_bitwise_operators_python_python_3.x.txt
Q: ValueError: invalid literal for int() with base 10: Python I have the following piece of code. I am reading from csv and am parsing its contents to a list: import csv finput = input.reader(open(path,'rb'),delimiter=',',quotechar='|') print finput[0] the output is: ['"1239"', '"2249.00"', '"1"', '"3"', '"2011-02-...
ValueError: invalid literal for int() with base 10: Python
I have the following piece of code. I am reading from csv and am parsing its contents to a list: import csv finput = input.reader(open(path,'rb'),delimiter=',',quotechar='|') print finput[0] the output is: ['"1239"', '"2249.00"', '"1"', '"3"', '"2011-02-20"'] Now I want to just extract the 1239 number... the first e...
[ "In brief:\nint(finput[0][0].strip('\"'))\n\nBut why have you set quotechar to |? Are you sure it shouldn't be \" instead? With it set to \", you should get strings without the quotes.\n", "Use strip().\nel = int(finput[0][0].strip('\"'))\n\n>>> a = '\"1234\"'\n>>> a\n'\"1234\"'\n>>> a.strip('\"')\n'1234'\n>>> ...
[ 7, 1 ]
[]
[]
[ "file_io", "python" ]
stackoverflow_0007896485_file_io_python.txt
Q: Error when inserting strings into SQLite database from Python code When I want to insert a string from Python code to SQLite database I get this error: sqlite3.ProgrammingError: You must not use 8-bit bytestrings unless you use a text_factory that can interpret 8-bit bytestrings (like text_factory = str). It ...
Error when inserting strings into SQLite database from Python code
When I want to insert a string from Python code to SQLite database I get this error: sqlite3.ProgrammingError: You must not use 8-bit bytestrings unless you use a text_factory that can interpret 8-bit bytestrings (like text_factory = str). It is highly recommended that you instead just switch your application to...
[ "SQLite only stores unicode strings. It is most likely the URL that isn't unicode so you'll need to convert it.\nYou can store the URL as a blob (binary) instead but that will make life more complicated later.\n", "Though it is not strictly necessary for an url you could store it as Unicode.\nBeautifulSoup works...
[ 3, 1 ]
[]
[]
[ "beautifulsoup", "character_encoding", "python", "sqlite", "unicode" ]
stackoverflow_0007893305_beautifulsoup_character_encoding_python_sqlite_unicode.txt
Q: Using msvcrt in 64-bit python ctypes I want to call msvcrt functions from 64-bit python using the ctypes package. I'm obviously doing it wrong. Is the right way to do it obvious? Python 2.7.2 (default, Jun 12 2011, 14:24:46) [MSC v.1500 64 bit (AMD64)] on win 32 Type "help", "copyright", "credits" or "license" for...
Using msvcrt in 64-bit python ctypes
I want to call msvcrt functions from 64-bit python using the ctypes package. I'm obviously doing it wrong. Is the right way to do it obvious? Python 2.7.2 (default, Jun 12 2011, 14:24:46) [MSC v.1500 64 bit (AMD64)] on win 32 Type "help", "copyright", "credits" or "license" for more information. >>> import ctypes >>> l...
[ "The default ctypes result type is a 32 bit integer but a file handle is pointer width, i.e. 64 bits. You are therefore losing half of the information in the file pointer.\nBefore you call fopen you must state that the result type is a pointer:\nlibc.fopen.restype = ctypes.c_void_p\nfp = libc.fopen(...)\nlibc.fclos...
[ 6 ]
[]
[]
[ "64_bit", "ctypes", "msvcrt", "python" ]
stackoverflow_0007896778_64_bit_ctypes_msvcrt_python.txt
Q: Why is this saying that the object is not subscriptable (Python) I'm trying to write a code that will detect if a list is a palindrome. Here is what I have so far- ##theSubList = raw_input("Input the list here") def isPalindrome( theSubList ) : return theSubList == theSubList[::-1] Why does this tell me that ...
Why is this saying that the object is not subscriptable (Python)
I'm trying to write a code that will detect if a list is a palindrome. Here is what I have so far- ##theSubList = raw_input("Input the list here") def isPalindrome( theSubList ) : return theSubList == theSubList[::-1] Why does this tell me that the "int" object is not subscriptable. The only way I can get this to ...
[ "In your comment, you've posted that your call to the function is isPalindrome(123454321), which is calling your function on a number. You need to call it on a string. Change your call to isPalindrome('123454321') and it should work.\n", "Do you mean something like:\ndef isPalindrome(a):\n return a == \"\".jo...
[ 2, 2 ]
[]
[]
[ "python" ]
stackoverflow_0007896910_python.txt
Q: Python Fuse calling 'readlink' 6 times in a row I am implementing a filesystem using Python Fuse. A directory contains only symlinks and as such I return S_IFLNK | 0777 on the getattr method. Now, when I do an ls on the directory, I notice that Linux calls readlink method 6 times in a row for each entry in the di...
Python Fuse calling 'readlink' 6 times in a row
I am implementing a filesystem using Python Fuse. A directory contains only symlinks and as such I return S_IFLNK | 0777 on the getattr method. Now, when I do an ls on the directory, I notice that Linux calls readlink method 6 times in a row for each entry in the directory. Is it a bug on my side or a normal behavior?...
[ "Well, it's definitely not ls calling readlink more than once. Unless you're calling it with unusual flags?\n$ls\nentropy share\n$ls -l\ntotal 0\nlrwxrwxrwx 1 entropy users 14 Aug 8 14:26 entropy -> /home/entropy/\nlrwxrwxrwx 1 entropy users 11 Aug 8 14:18 share -> /usr/share/\n$ltrace ls 2>&1 | grep readlink\n$...
[ 2, 1 ]
[]
[]
[ "fuse", "linux", "python" ]
stackoverflow_0003396503_fuse_linux_python.txt
Q: Using Python mechanize to log into websites? I'm using mechanize (and following this tutorial) to try to log into websites. I wanted to try to test it out on Twitter, so this is the script I came up with: import mechanize import cookielib username = 'user' # your username/email password = 'pass' # your passwo...
Using Python mechanize to log into websites?
I'm using mechanize (and following this tutorial) to try to log into websites. I wanted to try to test it out on Twitter, so this is the script I came up with: import mechanize import cookielib username = 'user' # your username/email password = 'pass' # your password br = mechanize.Browser() # set cookies cookie...
[ "I believe the last line should be:\nprint(br.response().read()) # print the response\n\nNotice the () after read. You are currently just printing the read method itself, not the result of calling the read method.\n" ]
[ 4 ]
[]
[]
[ "authentication", "mechanize", "python", "twitter" ]
stackoverflow_0007896829_authentication_mechanize_python_twitter.txt
Q: Why does setattr fail on a bound method In the following, setattr succeeds in the first invocation, but fails in the second, with: AttributeError: 'method' object has no attribute 'i' Why is this, and is there a way of setting an attribute on a method such that it will only exist on one instance, not for each ins...
Why does setattr fail on a bound method
In the following, setattr succeeds in the first invocation, but fails in the second, with: AttributeError: 'method' object has no attribute 'i' Why is this, and is there a way of setting an attribute on a method such that it will only exist on one instance, not for each instance of the class? class c: def m(self)...
[ "The short answer: There is no way of adding custom attributes to bound methods.\nThe long answer follows.\nIn Python, there are function objects and method objects. When you define a class, the def statement creates a function object that lives within the class' namespace:\n>>> class c:\n... def m(self):\n......
[ 34, 2 ]
[]
[]
[ "methods", "python", "python_3.x", "setattr" ]
stackoverflow_0007891277_methods_python_python_3.x_setattr.txt
Q: Pulling text from file with python I have a text file that I am opening in my python code. I want to search through the file and pull out the text that is followed by a specific symbol. For instance my text file name File.txt is: Hello, this is just a dummy file that has information with no substance at all and I...
Pulling text from file with python
I have a text file that I am opening in my python code. I want to search through the file and pull out the text that is followed by a specific symbol. For instance my text file name File.txt is: Hello, this is just a dummy file that has information with no substance at all and I want to pull the information between th...
[ "s = \"Hello, this is just a dummy file that has information with no substance at all and I want to pull the information between the dollar sign symbols. So all of this $ in between here should be pulled out so I can do what ever I want to with it $ and the rest of this will be a second group.\"\n\na = s.split(\"$\...
[ 1, 0, 0, 0 ]
[]
[]
[ "python", "string" ]
stackoverflow_0007897466_python_string.txt
Q: Python 2.7 - how do you write MeCab parsed information to a text file? I've written a GUI that allows Japanese input and when you go to file > parse writes in to a text file. That text file then gets run through MeCab where spaces are put in between the words. After that it is supposed to be written to the text fi...
Python 2.7 - how do you write MeCab parsed information to a text file?
I've written a GUI that allows Japanese input and when you go to file > parse writes in to a text file. That text file then gets run through MeCab where spaces are put in between the words. After that it is supposed to be written to the text file once again, so it can be displayed in another GUI window. The issue I'm h...
[ "The parsed data isn't unicode, it's a byte string.\nSo when you try to write the data to the file, it tries to decode it to unicode before encoding it to utf-8. Since your default codec is ascii, but you actually have utf-8, it chokes on the first character with byte value of 128 or above.\nYou should .decode('utf...
[ 4, 0 ]
[]
[]
[ "mecab", "parsing", "python", "unicode" ]
stackoverflow_0007892007_mecab_parsing_python_unicode.txt
Q: Python function syntax seems to be invalid, but runs All, I've run across a weird surprise in python today. The following code works, but seems to violate python's syntax. I don't know why it would work without a pass statement, or some code, but it does. def test(): '''Sample docstring.''' for i in range(10)...
Python function syntax seems to be invalid, but runs
All, I've run across a weird surprise in python today. The following code works, but seems to violate python's syntax. I don't know why it would work without a pass statement, or some code, but it does. def test(): '''Sample docstring.''' for i in range(10): test() print "testing", i I'd like to determine...
[ "There must be at least one statement in a block. A lone string literal is considered a valid statement, even if it is being used as the docstring. It should not cause any memory leaks though, since the compiler omits it in the actual code.\n", "Python's syntax is explained in the language reference. The relevant...
[ 11, 2, 0 ]
[]
[]
[ "memory_leaks", "python", "syntax" ]
stackoverflow_0007897715_memory_leaks_python_syntax.txt
Q: python split string IndexError import fileinput for line in fileinput.input("emaillist.txt"): line=line.rstrip('\n\r ') line= line.split('=') newlin = line[1] why is this not valid? I am trying to break up the nasty looking line of text and make something useful out of it? Doesnt the sp...
python split string IndexError
import fileinput for line in fileinput.input("emaillist.txt"): line=line.rstrip('\n\r ') line= line.split('=') newlin = line[1] why is this not valid? I am trying to break up the nasty looking line of text and make something useful out of it? Doesnt the split() function produce a list, which...
[ "You could use line.partition('=')[2] if '=' is sometimes missing:\n>>> 'a = b'.partition('=')\n('a ', '=', ' b')\n>>> 'a'.partition('=')\n('a', '', '')\n\nCompare it to split():\n>>> 'a = b'.split('=')\n['a ', ' b']\n>>> 'a'.split('=')\n['a']\n\n", "\nDoesnt the split() function produce a list, which you can add...
[ 4, 1, 0 ]
[]
[]
[ "python", "string" ]
stackoverflow_0007897839_python_string.txt
Q: Calling modules from Python dir() Short Question Is it possible to call a module as retrieved from the python dir() function? Background I am working on building a custom test runner and would like be able to choose which modules to run based on a string filter. See my examples below for ideal usage. module_a.p...
Calling modules from Python dir()
Short Question Is it possible to call a module as retrieved from the python dir() function? Background I am working on building a custom test runner and would like be able to choose which modules to run based on a string filter. See my examples below for ideal usage. module_a.py def not_mykey_dont_do_this(): pr...
[ "getattr(module_a, mod)()\n\ngetattr is a builtin function that takes and object and a string, and returns the attribute.\n", "Sure:\nimport module_a\nlist_from_a = dir(module_a)\n\nfor mod in list_from_a:\n if(mod.startswith('mykey_'):\n f = getattr(module_a, mod)\n f()\n\n" ]
[ 7, 5 ]
[]
[]
[ "python" ]
stackoverflow_0007898025_python.txt
Q: Hadoop cluster - Do I need to replicate my code over all machines before running job? This is what confuses me, when I use wordcount example, I keep code at master and let him do things with slaves and it runs fine But when I am running my code, it starts to fail on slaves giving weird errors like Traceback (m...
Hadoop cluster - Do I need to replicate my code over all machines before running job?
This is what confuses me, when I use wordcount example, I keep code at master and let him do things with slaves and it runs fine But when I am running my code, it starts to fail on slaves giving weird errors like Traceback (most recent call last): File "/app/hadoop/tmp/mapred/local/taskTracker/hduser/jobcache/job...
[ "With Hadoop Streaming, the code/dependencies have to be copied with the -file flag, if the code is not there on the target machine. Make sure that the map/reduce files and their dependencies are specified in the Hadoop streaming command.\n$HADOOP_HOME/bin/hadoop jar $HADOOP_HOME/hadoop-streaming.jar \\\n -inpu...
[ 6 ]
[]
[]
[ "hadoop", "hadoop_streaming", "mapreduce", "python" ]
stackoverflow_0007892950_hadoop_hadoop_streaming_mapreduce_python.txt
Q: Independent function or method I need to deal with a two objects of a class in a way that will return a third object of the same class, and I am trying to determine whether it is better to do this as an independent function that receives two objects and returns the third or as a method which would take one other o...
Independent function or method
I need to deal with a two objects of a class in a way that will return a third object of the same class, and I am trying to determine whether it is better to do this as an independent function that receives two objects and returns the third or as a method which would take one other object and return the third. For a s...
[ "The first approach is reasonable and isn't conceptually different from what set.union and set.intersection do. Any func(Point, Point) --> Point is clearly related to the Point class, so there is no question about interfering with the unity or cohesion of the class.\nIt would be a tougher choice if different clas...
[ 3, 2, 2, 1, 1, 0 ]
[]
[]
[ "api", "python", "readability" ]
stackoverflow_0007896935_api_python_readability.txt
Q: Coroutines in python I read the following code from a book, and have some questions about it. def coroutine(func): def start(*args, **kwargs): g = func(*args, **kwargs) g.next() return g return start @coroutine def receiver(): print("Ready to receive") while True: n...
Coroutines in python
I read the following code from a book, and have some questions about it. def coroutine(func): def start(*args, **kwargs): g = func(*args, **kwargs) g.next() return g return start @coroutine def receiver(): print("Ready to receive") while True: n = (yield) print("...
[ "Your problem isn't the coroutine. You're misunderstanding the function decorator. After r = receiver(), r is not start but g. Read up on function decoration and you'll understand what is going on.\n" ]
[ 2 ]
[]
[]
[ "coroutine", "decorator", "python" ]
stackoverflow_0007898296_coroutine_decorator_python.txt
Q: Is there a Python library (or pattern) like Ruby's andand? For example, I have an object x that might be None or a string representation of a float. I want to do the following: do_stuff_with(float(x) if x else None) Except without having to type x twice, as with Ruby's andand library: require 'andand' do_stuff_wi...
Is there a Python library (or pattern) like Ruby's andand?
For example, I have an object x that might be None or a string representation of a float. I want to do the following: do_stuff_with(float(x) if x else None) Except without having to type x twice, as with Ruby's andand library: require 'andand' do_stuff_with(x.andand.to_f)
[ "We don't have one of those but it isn't hard to roll your own:\ndef andand(x, func):\n return func(x) if x else None\n\n>>> x = '10.25'\n>>> andand(x, float)\n10.25\n>>> x = None\n>>> andand(x, float) is None\nTrue\n\n", "Taking off on Raymond's idea, here's a factory for making conditional wrappers of this s...
[ 9, 4 ]
[]
[]
[ "andand", "null", "python", "ruby" ]
stackoverflow_0007898688_andand_null_python_ruby.txt
Q: How to write unit test for Python socketserver request handler? How can I write unit tests for a socketserver request handler? I have tried to use the following code but have encountered a problem: import socketserver, unittest, threading class TestServer(socketserver.ThreadingMixIn, socketserver.TCPServer): ...
How to write unit test for Python socketserver request handler?
How can I write unit tests for a socketserver request handler? I have tried to use the following code but have encountered a problem: import socketserver, unittest, threading class TestServer(socketserver.ThreadingMixIn, socketserver.TCPServer): allow_reuse_address = True class MyRequestHandlerTest(unittest.TestC...
[ "It worked for me (after creating a RequestHandler) with:\ndef tearDown(self): \n self.client.close() \n self.server.shutdown()\n self.server.server_close()\n\nIt may be a bug in socketserver shutdown that it doesn't call server_close itself.\n" ]
[ 4 ]
[]
[]
[ "python", "sockets", "socketserver", "tcp", "unit_testing" ]
stackoverflow_0007720953_python_sockets_socketserver_tcp_unit_testing.txt
Q: how to encode a paragraph for use in a CSV file in python I am completely new to python and struggling to make a simple thing work. I am reading a bunch of information from a Web service, parsing the results, and I want to write it out into a flat-file. Most of my items are single line items, but one of the thing...
how to encode a paragraph for use in a CSV file in python
I am completely new to python and struggling to make a simple thing work. I am reading a bunch of information from a Web service, parsing the results, and I want to write it out into a flat-file. Most of my items are single line items, but one of the things I get back from my Web service is a paragraph. The paragraph ...
[ "The default csv.writer setup should handle this properly. Here's a simple example:\nimport csv\n\nmyparagraph = \"\"\"\nthis is a long paragraph, with \"quotes\" and stuff.\n\"\"\"\n\nmycsv = csv.writer(open('foo.csv', 'wb'))\nmycsv.writerow([myparagraph, 'word1'])\nmycsv.writerow(['word2', 'word3'])\n\nThis yiel...
[ 1, 0, 0 ]
[]
[]
[ "csv", "python" ]
stackoverflow_0007898382_csv_python.txt
Q: How do I access the name of a given variable in python? I am programming in python and need to access the name I have given to an object so as to be able to pass this as a string (concatenated with another string). The reason I need to do this is that the program I am using forces me to create a global (which in ...
How do I access the name of a given variable in python?
I am programming in python and need to access the name I have given to an object so as to be able to pass this as a string (concatenated with another string). The reason I need to do this is that the program I am using forces me to create a global (which in my case is a dictionary) and I am writing a function to work ...
[ "Your could do a reverse lookup of the names in globals():\n>>> NAME1 = 4\n>>> def name_of(value):\n for k, v in globals().items():\n if v is value:\n return k\n raise KeyError('did not find a name for %s' % value)\n\n>>> name_of(NAME1)\n'NAME1'\n\nIf the same object has been...
[ 8 ]
[]
[]
[ "object", "python" ]
stackoverflow_0007898831_object_python.txt
Q: popen3 and return code I want to get stdout and stderr of a command along with the return code. Can someone point me to a python function that already accomplishes this? I modified a function that I found on this site as follows -- but I am not able to grab the return code of the command. In this snippet, sts alw...
popen3 and return code
I want to get stdout and stderr of a command along with the return code. Can someone point me to a python function that already accomplishes this? I modified a function that I found on this site as follows -- but I am not able to grab the return code of the command. In this snippet, sts always seems to be 0. def Getst...
[ "Use the subprocess module. This section shows how to replace os.popen3 calls.\n" ]
[ 3 ]
[]
[]
[ "python" ]
stackoverflow_0007898900_python.txt
Q: Testing an outbound HTTP call with sockets? I'm trying to write a unit test for a webhooks callback in django. My application is set up so that, when I run a bit of code, it sends a POST request to the URL of my choice -- this is the functionality I'm trying to test. I'd like to set up a socket that listens for t...
Testing an outbound HTTP call with sockets?
I'm trying to write a unit test for a webhooks callback in django. My application is set up so that, when I run a bit of code, it sends a POST request to the URL of my choice -- this is the functionality I'm trying to test. I'd like to set up a socket that listens for this request and tells me if it was sent or not. I...
[ "The socket library cannot do this alone. Take a look at python twisted.\nThis should help you. Though I haven't tried it out with django yet. \n" ]
[ 1 ]
[]
[]
[ "asyncsocket", "django", "python", "sockets", "webhooks" ]
stackoverflow_0007896462_asyncsocket_django_python_sockets_webhooks.txt
Q: Single link clustering I'm looking for a way to do single link clustering with OpenCV. My scenario: Hundreds (potentially thousands) of feature vectors (vectors dimension can be up to ~800 features). Unknown number of clusters (likely to be much lower than the number of vectors). Fixed similarity threshold E - i...
Single link clustering
I'm looking for a way to do single link clustering with OpenCV. My scenario: Hundreds (potentially thousands) of feature vectors (vectors dimension can be up to ~800 features). Unknown number of clusters (likely to be much lower than the number of vectors). Fixed similarity threshold E - if the l1 norm between two ve...
[ "I'd suggest constructing a graph by your similarity threshold and finding connected components. Once you construct the graph, finding connected components will be fairly easy and efficient. If you like NetworkX already has a connected component function.\n", "I ended up doing an implementation by myself:\nimport...
[ 2, 0 ]
[]
[]
[ "cluster_analysis", "opencv", "python" ]
stackoverflow_0007831029_cluster_analysis_opencv_python.txt
Q: Default value with WSGIApplication Handler? I have the following code: class MyHandler(webapp.RequestHandler): def get(self, page_text, page=1): # page default value is 1, but it doesn't work application = webapp.WSGIApplication([('/something/(page(\d+))?/?', MyHandler)], debug=True) It should capture URLs l...
Default value with WSGIApplication Handler?
I have the following code: class MyHandler(webapp.RequestHandler): def get(self, page_text, page=1): # page default value is 1, but it doesn't work application = webapp.WSGIApplication([('/something/(page(\d+))?/?', MyHandler)], debug=True) It should capture URLs like: /something/ /something/page1 /something/page...
[ "Just a workaround waiting for some regex guru answer:\nclass MyHandler(webapp.RequestHandler):\n def get(self, page_text = None, page = 1)\n\napplication = webapp.WSGIApplication([('/something/', MyHandler)\n ('/something/(page(\\d+))?/?',MyHandler)], \n ...
[ 1, 0 ]
[]
[]
[ "google_app_engine", "python" ]
stackoverflow_0007864718_google_app_engine_python.txt
Q: Get matching elements' values in two arrays If a and b were lists of objects, each with a name property (e.g. a1 = A("1"), b1 = B("1"), etc.), how would I check for equivalency? I'm currently doing this: aList = [ a1, a2, a3, a4, a5 ] bList = [ b1, b2 ] aNameList = [] bNameList = [] for i in aList: aNameList....
Get matching elements' values in two arrays
If a and b were lists of objects, each with a name property (e.g. a1 = A("1"), b1 = B("1"), etc.), how would I check for equivalency? I'm currently doing this: aList = [ a1, a2, a3, a4, a5 ] bList = [ b1, b2 ] aNameList = [] bNameList = [] for i in aList: aNameList.append( i.name ) for i in bList: bNameList.ap...
[ "You can use list comprehensions instead to replace those temporary lists and for-loops of your example:\nmatch = set( [ x.name for x in aList ] ) & set ( [ x.name for x in bList ] )\n\n", "The operator.attrgetter function was designed for extracting fields of interest:\nset(map(attrgetter('name'), aList)) & set(...
[ 4, 0, 0 ]
[]
[]
[ "arrays", "python" ]
stackoverflow_0007899215_arrays_python.txt
Q: Python Logging monitor through http server Is there any tools that catches python logging (socket or http) handlers' reports, and serves a http service so that I can check my logs through a http page? Thanks Finally... I found a working server that will do the job... LoggingWebMonitor UPDATE I found Sentry on git...
Python Logging monitor through http server
Is there any tools that catches python logging (socket or http) handlers' reports, and serves a http service so that I can check my logs through a http page? Thanks Finally... I found a working server that will do the job... LoggingWebMonitor UPDATE I found Sentry on github, It seems more sophiscated and production-re...
[ "There are many to tools to easily create simple RESTful HTTP webservices. My favorite is itty.\nfrom itty import get, run_itty\nimport glob, gzip, json, os, functools\n\ndef jsonify(origfunc):\n @functools.wraps(origfunc)\n def wrapper(*args, **kwds):\n result = origfunc(*args, **kwds)\n retur...
[ 2, 1, 0 ]
[]
[]
[ "http", "logging", "python", "sockets" ]
stackoverflow_0007899103_http_logging_python_sockets.txt
Q: Python3 (v3.2.2) extra bits when writing binary files I have been working on function to map the bytes of a binary file to another set of bytes. I am reading from and writing to the same file. My problem is that every time i do it i end up with extra bytes unless i move to the end of the file before closing it, he...
Python3 (v3.2.2) extra bits when writing binary files
I have been working on function to map the bytes of a binary file to another set of bytes. I am reading from and writing to the same file. My problem is that every time i do it i end up with extra bytes unless i move to the end of the file before closing it, here is my code: with open(self._path,'r+b') as source: f...
[ "Comment (answer follows):\nI see the same behavior as you:\n#!/usr/bin/env python3\nimport os\nimport sys\n\nfilename = '/tmp/a'\nwith open(filename, 'wb') as f:\n f.write(b'1234a67b8ca')\nprint(open(filename, 'rb').read())\n\nbufsize = 3\n\ntable = bytes.maketrans(b'abcde', b'xyzzz') # mapping\nwith open(filen...
[ 3, 1 ]
[]
[]
[ "binaryfiles", "python", "python_3.x" ]
stackoverflow_0007899232_binaryfiles_python_python_3.x.txt
Q: Python - file management and processing multiple zip files I have some zip files in a folder. I have a script to process them. The data that is to be written to a database is in a different file and its structure is as follows: some_text;database;file_name some_text2;database2;file_name2 .... What is the best way...
Python - file management and processing multiple zip files
I have some zip files in a folder. I have a script to process them. The data that is to be written to a database is in a different file and its structure is as follows: some_text;database;file_name some_text2;database2;file_name2 .... What is the best way to process this file? Also, an error message should be reported...
[ "I know my code is far from perfect. The problem was with else. I moved it to the end of the whole code. It was a novice mistake. I also inserted try-catch so if it fails on one zip file, the next one is still processed. Now, it looks something like this:\nfilelist = glob.glob(os.path.join(rootdir, '*.zip'))\n if f...
[ 0 ]
[]
[]
[ "file", "python" ]
stackoverflow_0007888392_file_python.txt
Q: django template array element access hi: day_records is a array , i want to access element of it.if i replace the point with 0,or 1 , it's right , but when i use point , it can't access the element ,and with no syntax error. plant.bind("plothover", function(event,pos,item){ if(item){ rem...
django template array element access
hi: day_records is a array , i want to access element of it.if i replace the point with 0,or 1 , it's right , but when i use point , it can't access the element ,and with no syntax error. plant.bind("plothover", function(event,pos,item){ if(item){ removeTooltip(); var point = item....
[ "Your template code runs completely independently of JavaScript.\nThe browser runs JavaScript when the page loads, based on whatever raw code your template produced.\nGenerate a JavaScript array via the template language that your script can use, or use AJAX to request the data from django for a given point.\nday_r...
[ 1, 1 ]
[]
[]
[ "django", "python" ]
stackoverflow_0005785504_django_python.txt
Q: Django error with ORM I have started learning django and have a problem with INSERT-query using ORM (DB mysql). My model: class Record(models.Model): id = models.AutoField(primary_key=True, blank=True), schema_id = models.IntegerField(), name = models.CharField(max_length=50), desc ...
Django error with ORM
I have started learning django and have a problem with INSERT-query using ORM (DB mysql). My model: class Record(models.Model): id = models.AutoField(primary_key=True, blank=True), schema_id = models.IntegerField(), name = models.CharField(max_length=50), desc = models.TextField(bla...
[ "My guess is these commas in your model definition. \nYou are setting schema_id to a tuple of a model field. id = (models.AutoField(...),) \nRemove the trailing comma and you should be good to go.\nclass Record(models.Model):\n id = models.AutoField(primary_key=True, blank=True), # remove ,\n schema_i...
[ 6, 1 ]
[]
[]
[ "django", "django_models", "python" ]
stackoverflow_0007900162_django_django_models_python.txt
Q: Python oggenc script I want to write a python script (Yes not Bash) that will use flac files and encode them using oggenc and then on successful encoding delete the flac file. So far I have this: import os, sys import fnmatch command = 'oggenc -q7 *.flac' def main(): for root, dirs, files in os.walk('/home/w...
Python oggenc script
I want to write a python script (Yes not Bash) that will use flac files and encode them using oggenc and then on successful encoding delete the flac file. So far I have this: import os, sys import fnmatch command = 'oggenc -q7 *.flac' def main(): for root, dirs, files in os.walk('/home/wagnerf/test'): for...
[ "Use the subprocess module to call external commands, that offers more detailed control:\nfrom fnmatch import fnmatch\nimport os\nimport subprocess\n\ndef main():\n for root, dirs, files in os.walk('/home/wagnerf/test'):\n flacs = [f for f in files if fnmatch(f, '*.flac')]\n for f in flacs:\n ...
[ 1 ]
[]
[]
[ "python" ]
stackoverflow_0007900178_python.txt