text
stringlengths
226
34.5k
"overloading" doesn't work with stderr Question: /*---------------stdcallbk_module.h---------------------*/ #ifndef STDCALLBK_MODULE_H #include <Python.h> #define STDCALLBK_MODULE_H // Type definition for the callback function. typedef void __stdcall(CALLBK_FUNC_T)(const char* p); #ifdef __cplusplus extern "C" { #endif void register_callback(CALLBK_FUNC_T* callback); void import_stdcallbk(void); #ifdef __cplusplus } #endif #endif /* #define STDCALLBK_MODULE_H */ /*---------------stdcallbk_module.c---------------------*/ #include "stdcallbk_module.h" static CALLBK_FUNC_T *callback_write_func = NULL; static FILE *fp; /*for debugging*/ static PyObject* g_stdout; typedef struct { PyObject_HEAD CALLBK_FUNC_T *write; } Stdout; static PyObject* write2(PyObject* self, PyObject* args) { const char* p; if (!PyArg_ParseTuple(args, "s", &p)) return NULL; fputs(p, fp); fflush(fp); if(callback_write_func) callback_write_func(p); else printf("----%s----", p); return PyLong_FromLong(strlen(p)); } static PyObject* flush2(PyObject* self, PyObject* args) { // no-op return Py_BuildValue(""); } static PyMethodDef Stdout_methods[] = { {"write", write2, METH_VARARGS, "sys-stdout-write"}, {"flush", flush2, METH_VARARGS, "sys-stdout-write"}, {NULL, NULL, 0, NULL} }; static PyTypeObject StdoutType = { PyVarObject_HEAD_INIT(0, 0) "stdcallbk.StdoutType", /* tp_name */ sizeof(Stdout), /* tp_basicsize */ 0, /* tp_itemsize */ 0, /* tp_dealloc */ 0, /* tp_print */ 0, /* tp_getattr */ 0, /* tp_setattr */ 0, /* tp_reserved */ 0, /* tp_repr */ 0, /* tp_as_number */ 0, /* tp_as_sequence */ 0, /* tp_as_mapping */ 0, /* tp_hash */ 0, /* tp_call */ 0, /* tp_str */ 0, /* tp_getattro */ 0, /* tp_setattro */ 0, /* tp_as_buffer */ Py_TPFLAGS_DEFAULT, /* tp_flags */ "stdcallbk.Stdout objects", /* tp_doc */ 0, /* tp_traverse */ 0, /* tp_clear */ 0, /* tp_richcompare */ 0, /* tp_weaklistoffset */ 0, /* tp_iter */ 0, /* tp_iternext */ Stdout_methods, /* tp_methods */ 0, /* tp_members */ 0, /* tp_getset */ 0, /* tp_base */ 0, /* tp_dict */ 0, /* tp_descr_get */ 0, /* tp_descr_set */ 0, /* tp_dictoffset */ 0, /* tp_init */ 0, /* tp_alloc */ 0, /* tp_new */ }; static struct PyModuleDef stdcallbkmodule = { PyModuleDef_HEAD_INIT, "stdcallbk", /* name of module */ NULL, /* module documentation, may be NULL */ -1, /* size of per-interpreter state of the module, or -1 if the module keeps state in global variables. */ NULL, NULL, NULL, NULL, NULL }; PyMODINIT_FUNC PyInit_stdcallbk(void) { PyObject* m; fp = fopen("debuggered.txt", "wt"); fputs("got to here Vers 12\n", fp); fflush(fp); StdoutType.tp_new = PyType_GenericNew; if (PyType_Ready(&StdoutType) < 0) return 0; m = PyModule_Create(&stdcallbkmodule); if (m) { Py_INCREF(&StdoutType); PyModule_AddObject(m, "Stdout", (PyObject*) &StdoutType); fputs("PyModule_AddObject() Called\n", fp); fflush(fp); } g_stdout = StdoutType.tp_new(&StdoutType, 0, 0); /*PySys_SetObject("stdout", g_stdout)*/ fprintf(fp, "PySys_SetObject(stdout) returned %d\n", PySys_SetObject("stdout", g_stdout)); fflush(fp); /*PySys_SetObject("stderr", g_stdout)*/ fprintf(fp, "PySys_SetObject(stderr) returned %d\n", PySys_SetObject("stderr", g_stdout)); fflush(fp); return m; } /* called by cpp exe _after_ Py_Initialize(); */ void __declspec(dllexport) import_stdcallbk(void) { PyImport_ImportModule("stdcallbk"); } /* called by cpp exe _before_ Py_Initialize(); */ void __declspec(dllexport) register_callback(CALLBK_FUNC_T* callback) { PyImport_AppendInittab("stdcallbk", &PyInit_stdcallbk); callback_write_func = callback; } /*------------- Embarcadero C++ Builder exe ---------------------*/ #include "/py_module/stdcallbk_module.h" void __stdcall callback_write_func(const char* p) { ShowMessage(p); } //--------------------------------------------------------------------------- void __fastcall TForm1::Button1Click(TObject *Sender) { PyObject *pName, *pModule; register_callback(callback_write_func); Py_Initialize(); import_stdcallbk(); //PyRun_SimpleString("import stdcallbk\n"); pName = PyUnicode_FromString("hello_emb.py"); pModule = PyImport_Import(pName); Py_Finalize(); } //--------------------------------------------------------------------------- -------------- python script - hello_emb.py ---------------- #import stdcallbk print("HELLO FRED !") assert 1==2 ------------------------------------------------------------ The code above is borrowed from here: [How to redirect stderr in Python? Via Python C API?](http://stackoverflow.com/questions/1956407/how-to-redirect- stderr-in-python-via-python-c-api) When run from the cpp exe, I get a messagebox "HELLO FRED !" followed by an empty message box which I assume is the carriage return. All good so far, but when the exception is raised, I get nothing. Nothing is written to the text file either. But... if I uncomment the "import stdcallbk" from the python script and run it from the command line, I get this: D:\projects\embed_python3\Win32\Debug>hello_emb.py ----HELLO FRED !-------- --------Traceback (most recent call last): -------- File "D:\projects\embed_python3\Win32\Debug\hello_emb.py", line 7, in <module> -------- --------assert 1==2-------- --------AssertionError---------------- ---- and this: D:\projects\embed_python3\Win32\Debug>type debuggered.txt got to here Vers 12 PyModule_AddObject() Called PySys_SetObject(stdout) returned 0 PySys_SetObject(stderr) returned 0 HELLO FRED ! Traceback (most recent call last): File "D:\projects\embed_python3\Win32\Debug\hello_emb.py", line 7, in <module> assert 1==2 AssertionError So it DOES work, just not when it is run from the cpp exe. Anybody have any idea what on earth is going on here? Cheers Answer: Your assert will cause `hello_emb` import to fail. The body of the module is executed when a module is imported. In your case this happens inside the `PyImport_Import()` call. It will print "HELLO FRED!" just fine but then it will get to the assert which will raise an exception. `PyImport_Import()` will return `NULL` to indicate that. You have to check for that and take appropriate action (which may not always be to print the traceback, that's why it's left up to you). If you want to print the error to stderr, you have to call `PyErr_Print()`. pName = PyUnicode_FromString("hello_emb.py"); pModule = PyImport_Import(pName); if (pModule == NULL) PyErr_Print(); _Unrelated problems with the code:_ That's not the only place that is missing checks for errors (but only the above one is the reason for missing traceback). Calls to `fopen` or pretty much any Python C/API call can fail and you should handle that. Also, there's a reference leak in `PyInit_stdcallbk`. Right after you create the stdout object, its reference count is 1. Then you set it to `sys.stdout` and `sys.stderr` which makes it 3. After that you should `Py_DECREF` it to make it 2 so that if/when it is removed from `stdout` and `stderr`, it will be freed from memory. Right now it will never be freed.
Python multiprocessing pipe will not recv() properly Question: This is for Python 3.2.2. I'm only just learning how Python and multiprocessing work and this simple example has been tripping me: from multiprocessing import Pipe, Process def f(r): print(r.recv()) if __name__ == '__main__': q, r = Pipe() p = Process(target=f, args=(r,)) p.start() q.send([42, None, 'hello']) p.join() The main thread creates a new `Process`, `p`, and sends `r`, a bidirectional connection object, to function `f()`. When process `p` is started, I expect `r.recv()` to block (which, as far as I understand, means that this process will wait indefinitely until something comes through the pipe) until the main process sends some objects through with `q.send`. Then `p.join()` should make the main process wait until `p` has run its course. But nothing whatsoever happens. If I add a `print` statement to `f()`, nothing happens there, either, as if `f()` never even runs and `p.start()` is nonfunctional. Can you explain why this won't work and what might be fixed? Answer: I know it's been a while, but for others with this problem, you have the ends of your pipe reversed. You're trying to use the receiving end to send, and trying to receive with the sending end. I find that adding duplex=True to the Pipe constructor makes it much easier to deal with the different ends. Source: <https://docs.python.org/2/library/multiprocessing.html#pipes-and- queues>
How to use ebay sdk in Python? Question: I have found this code sample to make a query in ebay from [here](http://code.google.com/p/ebay-sdk-python/) and also downloaded ebay-sdk for Python. How can I install the sdk and integrate this code with it? from ebaysdk import finding, nodeText f = finding() f.execute('findItemsAdvanced', {'keywords': 'shoes'}) dom = f.response_dom() mydict = f.response_dict() myobj = f.response_obj() print myobj.itemSearchURL # process the response via DOM items = dom.getElementsByTagName('item') for item in items: print nodeText(item.getElementsByTagName('title')[0]) Answer: It is quite a simple process 1) Go to <http://developer.ebay.com/>, register over there, and get the app id key. 2) You can simply do a 'pip install ebaysdk' to install the ebaysdk 3) Copy this file in the same directory <https://github.com/timotheus/ebaysdk- python/blob/master/ebay.yaml> In this file replace _appid_ with what you generated in step 1 4) Execute the example, this time it will work :)
How to parse multiple sub-commands using python argparse? Question: I am implementing a command line program which has interface like this: cmd [GLOBAL_OPTIONS] {command [COMMAND_OPTS]} [{command [COMMAND_OPTS]} ...] I have gone through the [argparse documentation](http://docs.python.org/dev/library/argparse.html). I can implement `GLOBAL_OPTIONS` as optional argument using `add_argument` in `argparse`. And the `{command [COMMAND_OPTS]}` using [Sub- commands](http://docs.python.org/dev/library/argparse.html#sub-commands). From the documentation it seems I can have only one sub-command. But as you can see I have to implement one or more sub-commands. What is the best way to parse such command line arguments useing `argparse`? Answer: @mgilson has a nice [answer](http://stackoverflow.com/a/10449310/446386) to this question. But problem with splitting sys.argv myself is that i lose all the nice help message Argparse generates for the user. So i ended up doing this: import argparse ## This function takes the 'extra' attribute from global namespace and re-parses it to create separate namespaces for all other chained commands. def parse_extra (parser, namespace): namespaces = [] extra = namespace.extra while extra: n = parser.parse_args(extra) extra = n.extra namespaces.append(n) return namespaces argparser=argparse.ArgumentParser() subparsers = argparser.add_subparsers(help='sub-command help', dest='subparser_name') parser_a = subparsers.add_parser('command_a', help = "command_a help") ## Setup options for parser_a ## Add nargs="*" for zero or more other commands argparser.add_argument('extra', nargs = "*", help = 'Other commands') ## Do similar stuff for other sub-parsers Now after first parse all chained commands are stored in `extra`. I reparse it while it is not empty to get all the chained commands and create separate namespaces for them. And i get nicer usage string that argparse generates.
matplotlib, define size of a grid on a plot Question: I am plotting using matplotlib in python. I want create plot with grid, here is an [example](http://www.scipy.org/Plotting_Tutorial) from plotting tutorial. In my plot range if the y axe is from 0 to 14 and if use `pylab.grid(True)` then it makes grid with size of square of two, but I want the size to be 1. How can I force it? Answer: Try using `ax.grid(True, which='both')` to position your grid lines on both major and minor ticks, as suggested [here](http://matplotlib.sourceforge.net/api/axis_api.html). EDIT: Or just set your ticks manually, like this: import matplotlib.pyplot as plt fig = plt.figure() ax = fig.add_subplot(111) ax.plot([1,2,3,14],'ro-') # set your ticks manually ax.xaxis.set_ticks([1.,2.,3.,10.]) ax.grid(True) plt.show()
Python: What's the right way to make modules visible to a TestRunner? Question: after watching a couple of presentations about django testing, I want to code my own TestRunner in order to skip django tests, and create better packages structures for my tests. The problem is that we've changed the project structure and the test runner can't find the right path to do the tests discovery. This is how my project looks like: project/ -src/ - project_name/ - apps/ - test/ # Not a good name, i know, will change it - some_app/ - test_models.py - manage.py - development.db Now, in order to test `test_models.py` I want to do this: $ cd project/src/ $ python manage.py test some_app.test_models The problem is that the test runner can't find that package (`some_app`) and module (`test_models.py`). It changes if I hardcode the name in the test runner, but i don't like to do it. Here's what I do to make it work. test_labels = ["%s.%s" % ("project_name.test", l) for l in test_labels if not l.startswith("project_name.test")] So, if you do $ python manage.py test some_app.test_models It will be rewritten to: $ python manage.py test project_name.test.some_app.test_models And that works fine. I tried doing `sys.path.append("(...)/project_name/test)` but doesn't work neither. This is the code of my TestRunner: class DiscoveryDjangoTestSuiteRunner(DjangoTestSuiteRunner): """A test suite runner that uses unittest2 test discovery. It's better than the default django test runner, becouse it doesn't run Django tests and let you put your tests in different packages, modules and classes. To test everything in there: $ ./manage.py test To test a single package/module: $ ./manage.py test package $ ./manage.py test package.module To test a single class: $ ./manage.py test package.module.ClassName """ def build_suite(self, test_labels, extra_tests=None, **kwargs): suite = None discovery_root = settings.TEST_DISCOVERY_ROOT if test_labels: # This is where I append the path suite = defaultTestLoader.loadTestsFromNames(test_labels) # if single named module has no tests, do discovery within it if not suite.countTestCases() and len(test_labels) == 1: suite = None discovery_root = import_module(test_labels[0]).__path__[0] if suite is None: suite = defaultTestLoader.discover( discovery_root, top_level_dir=settings.BASE_PATH, ) if extra_tests: for test in extra_tests: suite.addTest(test) return reorder_suite(suite, (TestCase,)) Answer: Before you continue investing more time into your custom `TestRunner`, I would definitely recommend that you take a look at [`django- nose`](https://github.com/jbalogh/django-nose). The custom test runner provided by `django-nose` implements [`nose`](http://readthedocs.org/docs/nose/en/latest/)'s test runner which is extremely flexible and provides a lot of options for running your tests. It seamlessly overrides the default `test` management command and allows you to configure default test options in your project's `settings` module. I'm really recommending it for several reasons: * The options for the `test` command are fully documented ([take look at the output](https://gist.github.com/2597247)) * nose provides _a lot_ of approaches for [test discovery](http://readthedocs.org/docs/nose/en/latest/finding_tests.html) * Chances are your colleagues are already seasoned nose users * You didn't have to write the `TestRunner` class yourself
Recursive Searching and MySql Comparison Question: Good evening. I am looking at developing some code that will collect EXIF data from JPEG images and store it in a MySQL database using Python v2.x The stumbling block lies in the fact that the JPEGs are scattered in a number of subdirectories and further subdirectories in a root folder so for example 200 JPEGs may be stored in root > subroot > subsubroot1 as well as a further 100 in root > subroot > subroot2. Once all images are identified, they will be scanned and their respective EXIF data abstracted before being added to a MySQL table. At the moment I am just at the planning stage but I am just wondering, what would be the most efficient and pythonic way to carry out the recursive searching? I am looking to scan the root directory and append any new identified subdirectories to a list and then scan all subdirectory paths in the list for further subdirectories until I have a total list of all directories. This just seems to be a clumsy way though IMHO and a bit repetitive so I assume there may be a more OOP manner of carrying out this function. Similarly, I am only looking to add new info to my MySQL table and so what would be the most efficient way to establish if an entry already exists? The filename both in the table and the JPEG file name will be its MD5 hash values. I was considering scanning through the table at the beginning of the code and placing all filenames in a set and so, before scanning a new JPEG, if an entry already exists in the set, there would be no need to extract the EXIF and move onto the next picture. Is this an efficient method however or would it be better to scan through the MySQL table when a new image is encountered? I anticipate the set method may be the most efficient however the table may potentially contain tens of millions of entries eventually and so to add the filenames for these entries into a set (volatile memory) may not be the best idea. Thanks folks. Answer: I would just write a function that scanned a directory for all files; if it's a jpeg, add the full path name of the jpeg to the list of results. If it's a directory, then immediately call the function with the newly discovered directory as an argument. If it's another type of file, do nothing. This is a classic recursive divide-and-conquer strategy. It will break if there are loops in your directory path, for instance with symlinks -- if this is a danger for you, then you'll have to make sure you don't traverse the same directory twice by finding the "real" non-symlinked path of each directory and recording it. How to avoid duplicate entries is a trickier problem and you have to consider whether you are tolerant of two differently-named files with the exact same contents (and also consider the edge cases of symlinked or multiply-hard- linked files), how new files appear in the directories you are scanning and whether you have any control over that process. One idea to speed it up would be to use [os.path.getmtime()](http://docs.python.org/library/os.path.html#os.path.getmtime). Record the moment you start the directory traversal process. Next time around, have your recursive traversal process ignore any jpeg files with an mtime older than your recorded time. This can't be your only method of keeping track because files modified between the start and end times of your process may or may not be recorded, so you will still have to check the database for those records (for instance using the full path, a hash on the file info or a hash on the data itself, depending on what kind of duplication you're intolerant of) but used as a heuristic it should speed up the process greatly. You could theoretically load all filenames (probably paths and not filenames) from the database into memory to speed up comparison, but if there's any danger of the table becoming very large it would be better to leave that info in the database. For instance, you could create a hash from the filename, and then simply add that to the database with a UNIQUE constraint -- the database will reject any duplicate entries, you can catch the exception and go on your way. This won't be slow if you use the aforementioned heuristic checking file mtime. Be sure you account for the possibility of files that may be only modified and not newly created, if that's important for your application.
Python: how to get correct list when split? Question: In test.txt, I have 2 lines of sentences. The heart was made to be broken. There is no surprise more magical than the surprise of being loved. The code: import re file = open('/test.txt','r')#specify file to open data = file.readlines() file.close() for line in data: line_split = re.split(r'[ \t\n\r, ]+',line) print line_split Results from the codes: ['The', 'heart', 'was', 'made', 'to', 'be', 'broken.', ''] ['There', 'is', 'no', 'surprise', 'more', 'magical', 'than', 'the', 'surprise', 'of', 'being', 'loved.'] How to get only word print out? (see the first sentence) Expect result: ['The', 'heart', 'was', 'made', 'to', 'be', 'broken.'] ['There', 'is', 'no', 'surprise', 'more', 'magical', 'than', 'the', 'surprise', 'of', 'being', 'loved.'] Any advice? Answer: Instead of using `split` to match the delimiters, you can use `findall` with the negated regular expression to match the parts you want to keep: line_split = re.findall(r'[^ \t\n\r., ]+',line) See it working online: [ideone](http://ideone.com/OV2dq)
plpgsql - bytes are not getting unpacked right Question: I wrote a function in plpgsql `unpack_numeric_bytes`, the most important part of the functions is: FOR i IN 1..v_length LOOP v_val := v_val + (get_byte(v_bytes, v_byte_index) << v_bit_shift); v_bit_shift := v_bit_shift + 8; v_byte_index := v_byte_index + 1; END LOOP; It has worked fine until I came across value that it didnt decode correctly.. and it might be too obvious but I am not seeing it. The call is: `select unpack_numeric_bytes(E'g\\363I\\274', array[4], 'f');` From the code `v_length` is 4 bytes and it tries to decode `E'g\\363I\\274'` Which comes up to : `{-1136004249}`.. I noticed that 2^32 - 1136004249 = 3158963047, and that is the right answer I am looking for ! (tested it with python unpack function). What is throwing it off? and what am I doing wrong? This is the first time the function failed me. Thanks! Answer: Found what the problem was: select ('10111100000000000000000000000000'::bit(32))::integer; int4 | -1140850688 -- versus select (('10111100000000000000000000000000'::bit(32))::bigint); int8 | 3154116608 Fixed this line: v_val := v_val + (get_byte(v_bytes, v_byte_index)::BIGINT << v_bit_shift)::BIGINT;
simple python "printing own arguments" Question: I've just discovered that in my course, the lecturer doesn't want us to use the 'import' function, as it's apparently 'too advanced for the student's needs at this point.' Messing around with what I am "allowed" to use, I've come up with this: #!/usr/bin/python moo = raw_input ('moo ') string = ''.join(moo) outp = string.split() for word in outp: print word which gives me $ ./pecho moo hello world hello world How to I fiddle with _what I've got here_ to put the "hello world" output on one line? * * * Original post: I need to create a python file that "simply prints its own arguments, each separated by one space." For example, the following command will give the output shown: $ pecho first and then another one first and then another one $ IS THIS simply something like #!/usr/bin/python moo = raw_input ('moo ') print moo ? If so, how do I make it so that it prints exactly only one space between the words in the output, regardless of how many tabs/spaces there are in the input? Answer: Here's the answer to the revised question: moo = raw_input ('moo ') print ' '.join(moo.split()) Starting from the inside of the parens, we first take the input `moo` and split it up into pieces based on the whitespace. That gives us an iterable list, similar to `sys.argv` in the old answer. Then, I join that list using join, and a single space. Then print the whole deal. To understand this better, here is the same thing, but using more lines: moo = raw_input('moo ') temp_list = moo.split() print ' '.join(temp_list) Try printing the temp_list too, to see what it looks like. Just add this as the last line, to see how a list is printed: print temp_list * * * You probably want this: import sys if len(sys.argv) > 1: for arg in sys.argv[1:]: print arg, sys.argv is a list of the command line arguments. The first one is the name of your script. A [list](http://docs.python.org/library/functions.html#list) is an iterable type, so you can use the [for](http://docs.python.org/tutorial/controlflow.html) loop to iterate on it. I split the list such that I start with the second item in it. I use a comma at the end of the print line to tell python not to print a newline. There's a different method for doing that in python 3. In [python 3](http://docs.python.org/release/3.0.1/whatsnew/3.0.html) the last line would be: print(arg, end=" ") To use [Dan D](http://stackoverflow.com/users/388787/dan-d)'s example you would just do: import sys if len(sys.argv) > 1: print ' '.join(sys.argv[1:]) You could still test to make sure you have at least one more arg than your script name. It [joins](http://docs.python.org/library/stdtypes.html#str.join) together the iterable list with a space in between each item.
Write curl in python code Question: > **Possible Duplicate:** > [CURL alternative in > Python](http://stackoverflow.com/questions/2667509/curl-alternative-in- > python) I'm trying to write a python snippet that returns a JSON response. With curl it works and look like this: curl -H 'content-type: application/json' \ -d '' http://example.com/postservice.get_notes How could I write code in python that returns a JSON object as the curl command does? Answer: To **exactly mimic** this you'll need [pycurl](http://pycurl.sourceforge.net/). import pycurl import StringIO  buf = StringIO.StringIO() c = pycurl.Curl() c.setopt(c.URL, 'http://example.com/postservice.get_notes') c.setopt(c.WRITEFUNCTION, buf.write) c.setopt(c.HTTPHEADER, ['Accept-Charset: UTF-8']) c.setopt(c.POSTFIELDS, '') c.perform() json = buf.getvalue() buf.close() **Note** here `content-type: application/json` is not a valid request header. So it's not needed.
HTML/JS as interface to local SQLite database Question: I'm writing a pretty simple database application, which I want to be locally stored (as opposed to looking up a remote database). I like HTML/Javascript for designing interfaces, and they're cross-platform (everybody has a browser!), so I'd really like to write a webpage as a frontend. No client/server interaction should be involved - I just want the users to be able to interact with the database using a browser, instead of a native program. However, the only way I can see to access databases from a browser is using something like WebSQL or IndexedDB. Both of these, however, abstract away the process of managing the database file itself, and store it away in user settings somewhere. I want to distribute the database file itself along with the app. In short: is there a way to use HTML/Javascript to modify a local SQLite database file? Or is HTML not the tool I should be using for this sort of application? _EDIT:_ [possibly relevant](http://stackoverflow.com/questions/877033/how-can- i-create-an-local-webserver-for-my-python-scripts) Answer: This is what I've ended up doing: As referred to [here](http://stackoverflow.com/questions/877033/how-can-i- create-an-local-webserver-for-my-python-scripts), you can use Python to create a local web server. [This](http://fragments.turtlemeat.com/pythonwebserver.php) tutorial gives a basic infrastructure for the server handler. I had to deal with some issues, possibly caused by Python 3 or by using Chrome to access my local page. My GET handler function ended up looking like this: def do_GET(self): try: self.send_response(200) self.send_header('Content-type', 'text/html') self.send_header('Access-Control-Allow-Origin', '*') self.end_headers() try: fn = GETHANDLERS[self.path[1:]] self.wfile.write(fn().encode("utf-8")) except KeyError: self.wfile.write(self.path.encode("utf-8")) return except: self.send_error(404, 'File Not Found: {0}'.format(self.path)) Where `GETHANDLERS` is a dictionary mapping URLs to functions - for example, if you visit `http://localhost/my_func`, the `GETHANDLERS['my_func']` function is called. If no function exists for the URL, the URL is just echoed back. I've implemented functions that manipulate a local SQLite database with the `sqlite3` module. Here's an example of the query to list everything in the `Categories` table: import sqlite3 def get_categories(): con = sqlite3.connect('my.db') c = con.cursor() c.execute('''SELECT * FROM Categories;''') return [cat[0] for cat in c.fetchall()] GETHANDLERS["categories"] = get_categories To use the local app, it's necessary for the user to install Python, then run the server script before opening the webpage. I think this is pretty acceptable!
Calculating cartesian coordinates using python Question: Having not worked with cartesian graphs since high school, I have actually found a need for them relevant to real life. It may be a strange need, but I have to allocate data to points on a cartesian graph, that will be accessible by calling cartesian coordinates. There needs to be infinite points on the graphs. For Eg. ^ [-2-2,a ][ -1-2,f ][0-2,k ][1-2,p][2-2,u] [-2-1,b ][ -1-1,g ][0-1,l ][1-1,q][1-2,v] <[-2-0,c ][ -1-0,h ][0-0,m ][1-0,r][2-0,w]> [-2--1,d][-1--1,i ][0--1,n][1-1,s][2-1,x] [-2--2,e][-1--2,j ][0--2,o][1-2,t][2-2,y] v The actual values aren't important. But, say I am on variable m, this would be 0-0 on the cartesian graph. I need to calculate the cartesian coordinates for if I moved up one space, which would leave me on l. Theoretically, say I have a python variable which == ("0-1"), I believe I need to split it at the -, which would leave x=0, y=1. Then, I would need to perform (int(y)+1), then re-attach x to y with a '-' in between. What I want to be able to do is call a function with the argument (x+1,y+0), and for the program to perform the above, and then return the cartesian coordinate it has calculated. I don't actually need to retrieve the value of the space, just the cartesian coordinate. I imagine I could utilise re.sub(), however I am not sure how to format this function correctly to split around the '-', and I'm also not sure how to perform the calculation correctly. How would I do this? Answer: To represent an infinite lattice, use a dictionary which maps tuples (x,y) to values. grid[(0,0)] = m grid[(0,1)] = l print(grid[(0,0)])
In Go, how do I capture stdout of a function into a string? Question: In Python, for example, I can do the following: realout = sys.stdout sys.stdout = StringIO.StringIO() some_function() # prints to stdout get captured in the StringIO object result = sys.stdout.getvalue() sys.stdout = realout Can you do this in Go? Answer: I agree you should use the `fmt.Fprint` functions if you can manage it. However, if you don't control the code whose output you're capturing, you may not have that option. Mostafa's answer works, but if you want to do it without a temporary file you can use [os.Pipe](http://golang.org/pkg/os/#Pipe). Here's an example that's equivalent to Mostafa's with some code inspired by Go's testing package. package main import ( "bytes" "fmt" "io" "os" ) func print() { fmt.Println("output") } func main() { old := os.Stdout // keep backup of the real stdout r, w, _ := os.Pipe() os.Stdout = w print() outC := make(chan string) // copy the output in a separate goroutine so printing can't block indefinitely go func() { var buf bytes.Buffer io.Copy(&buf, r) outC <- buf.String() }() // back to normal state w.Close() os.Stdout = old // restoring the real stdout out := <-outC // reading our temp stdout fmt.Println("previous output:") fmt.Print(out) }
How do I find the angle between 2 points in pygame? Question: I am writing a game in Python with Pygame. The co-ords (of my display window) are `( 0 , 0 )` at the top left and `(640,480)` at the bottom right. The angle is `0°` when pointing up, `90°` when pointing to the right. I have a player sprite with a centre position and I want the turret on a gun to point towards the player. How do I do it? Say, `x1`,`y1` are the turret co-ords `x2`,`y2` are the player co-ords `a` is the angle's measure Answer: First, `math` has a handy `atan2(denominator, numerator)` function. Normally, you'd use `atan2(dy,dx)` but because Pygame flips the y-axis relative to Cartesian coordinates (as you know), you'll need to make `dy` negative and then avoid negative angles. ("dy" just means "the change in y".) from math import atan2, degrees, pi dx = x2 - x1 dy = y2 - y1 rads = atan2(-dy,dx) rads %= 2*pi degs = degrees(rads) `degs` ought to be what you're looking for.
Is it possible to monitor every file creation on a Windows drive? Question: I'm writing a program in Python that stores information for every file on the system. When it's installed, it will walk over every file, but afterwards I want to update it whenever a new file is created, or when a file is moved. For example, In the Dropbox service, whenever I copy a file into my Dropbox dir, it immediately notices and uploads it to their server. Is there a way to do this in Python without polling? I'm thinking about some sort of an event listener that is triggered when a file is created. Answer: Try one of: * <http://pypi.python.org/pypi/watcher> * <http://pypi.python.org/pypi/watchdog> I think first of them is simpler to use. Example of use (from its site): import watcher w = watcher.Watcher(dir, callback) w.flags = watcher.FILE_NOTIFY_CHANGE_FILE_NAME w.start() watcher is module that wraps system API, and is described on MSDN: <http://msdn.microsoft.com/en-us/library/aa365465(v=vs.85).aspx> So, flag `watcher.FILE_NOTIFY_CHANGE_FILE_NAME` says that you will be notified about: > Any file name change in the watched directory or subtree causes a change > notification wait operation to return. Changes include renaming, creating, > or deleting a file.
How to send a zip file as an attachment in python? Question: I have looked through many tutorials, as well as other question here on stack overflow, and the documentation and explanation are at minimum, just unexplained code. I would like to send a file that I already have zipped, and send it as an attachment. I have tried copy and pasting the code provided, but its not working, hence I cannot fix the problem. So what I am asking is if anyone knows who to explain how smtplib as well as email and MIME libraries work together to send a file, more specifically, how to do it with a zip file. Any help would be appreciated. This is the code that everyone refers to: import smtplib import zipfile import tempfile from email import encoders from email.message import Message from email.mime.base import MIMEBase from email.mime.multipart import MIMEMultipart def send_file_zipped(the_file, recipients, sender='[email protected]'): myzip = zipfile.ZipFile('file.zip', 'w') # Create the message themsg = MIMEMultipart() themsg['Subject'] = 'File %s' % the_file themsg['To'] = ', '.join(recipients) themsg['From'] = sender themsg.preamble = 'I am not using a MIME-aware mail reader.\n' msg = MIMEBase('application', 'zip') msg.set_payload(zf.read()) encoders.encode_base64(msg) msg.add_header('Content-Disposition', 'attachment', filename=the_file + '.zip') themsg.attach(msg) themsg = themsg.as_string() # send the message smtp = smtplib.SMTP() smtp.connect() smtp.sendmail(sender, recipients, themsg) smtp.close() I suspect the issue is this code zips a file as well. I don't want to zip anything as I already have a zipped file I would like to send. In either case, this code is poorly documented as well as the python libraries themselves as they provide no insight on anything past img file and text files. UPDATE: Error I am getting now. I have also updated what is in my file with the code above Traceback (most recent call last): File "/Users/Zeroe/Documents/python_hw/cgi-bin/zip_it.py", line 100, in <module> send_file_zipped('hw5.zip', '[email protected]') File "/Users/Zeroe/Documents/python_hw/cgi-bin/zip_it.py", line 32, in send_file_zipped msg.set_payload(myzip.read()) TypeError: read() takes at least 2 arguments (1 given) Answer: I don't really see the problem. Just omit the part which creates the zip file and, instead, just load the zip file you have. Essentially, this part here msg = MIMEBase('application', 'zip') msg.set_payload(zf.read()) encoders.encode_base64(msg) msg.add_header('Content-Disposition', 'attachment', filename=the_file + '.zip') themsg.attach(msg) creates the attachment. The msg.set_payload(zf.read()) sets, well, the payload of the attachment to what you read from the file `zf` (probably meaning zip file). Just open your zip file beforehand and let this line read from it.
After successful installation of cjklib and CEDICT, when I use it, it throw errors, why? Question: This is my first post here. I have been reading posts here since I started learning python and it has been nothing but a great help to my learning process. So, just want to say A BIG THANK YOU to you all before my question! **Question:** I installed the cjklib package successfully. Then, I installed the CEDICT dictionary successfully as well. But when I try to use CEDICT, it always throws errors like this: >>> d = CEDICT() ...... File "build/bdist.linux-x86_64/egg/sqlalchemy/engine/default.py", line 335, in do_execute sqlalchemy.exc.OperationalError: (OperationalError) unknown database "cedict_0" 'PRAGMA "cedict_0".table_info("CEDICT")' () >>> **To reproduce the problem:** _Install the cjklib package:_ Download the cjklib-0.3.tar.gz, extract it and update the files in directory Cjklib-0.3/cjklib/build/*.py (specifically, builder.py and **init**.py): Update "from sqlalchemy.exceptions" to "from sqlalchemy.exc" $cd djklib-0.3/cjklib/build/ $sudo python setup.py install $sudo installcjkdict CEDICT $python Python 2.7.3 (default, Apr 20 2012, 22:39:59) [GCC 4.6.3] on linux2 Type "help", "copyright", "credits" or "license" for more information. >>> from cjklib.dictionary import CEDICT >>> d = CEDICT() The error occurs, in details, as below: >>> d = CEDICT() Traceback (most recent call last): File "<stdin>", line 1, in <module> File "/usr/local/lib/python2.7/dist-packages/cjklib/dictionary/__init__.py", line 605, in __init__ super(CEDICT, self).__init__(**options) File "/usr/local/lib/python2.7/dist-packages/cjklib/dictionary/__init__.py", line 532, in __init__ super(EDICTStyleEnhancedReadingDictionary, self).__init__(**options) File "/usr/local/lib/python2.7/dist-packages/cjklib/dictionary/__init__.py", line 269, in __init__ if not self.available(self.db): File "/usr/local/lib/python2.7/dist-packages/cjklib/dictionary/__init__.py", line 276, in available and dbConnectInst.hasTable(cls.DICTIONARY_TABLE)) File "/usr/local/lib/python2.7/dist-packages/cjklib/dbconnector.py", line 444, in hasTable schema = self._findTable(tableName) File "/usr/local/lib/python2.7/dist-packages/cjklib/dbconnector.py", line 429, in _findTable if hasTable(tableName, schema=schema): File "build/bdist.linux-x86_64/egg/sqlalchemy/engine/base.py", line 2525, in has_table File "build/bdist.linux-x86_64/egg/sqlalchemy/engine/base.py", line 2412, in run_callable File "build/bdist.linux-x86_64/egg/sqlalchemy/engine/base.py", line 1959, in run_callable File "build/bdist.linux-x86_64/egg/sqlalchemy/dialects/sqlite/base.py", line 567, in has_table File "build/bdist.linux-x86_64/egg/sqlalchemy/engine/base.py", line 1450, in execute File "build/bdist.linux-x86_64/egg/sqlalchemy/engine/base.py", line 1627, in _execute_text File "build/bdist.linux-x86_64/egg/sqlalchemy/engine/base.py", line 1697, in _execute_context File "build/bdist.linux-x86_64/egg/sqlalchemy/engine/base.py", line 1690, in _execute_context File "build/bdist.linux-x86_64/egg/sqlalchemy/engine/default.py", line 335, in do_execute sqlalchemy.exc.OperationalError: (OperationalError) unknown database "cedict_0" 'PRAGMA "cedict_0".table_info("CEDICT")' () >>> **Tryouts:** I tried some solutions myself, like: As the error indicated, it can't find the table in the sqlite database file, so I edited the cjklib.conf file by adding following the line to tell it that the table is right here: url = sqlite:////usr/local/share/cjklib/cedict.db Then, it found the table CEDICT and stopped throwing the errors. But unfortunately, it started throwing another kind of error when I ran the code below: >>> from cjklib import characterlookup >>> cjk = characterlookup.CharacterLookup('T') Error: >>> cjk = characterlookup.CharacterLookup('T') Traceback (most recent call last): File "<stdin>", line 1, in <module> File "/usr/local/lib/python2.7/dist-packages/cjklib/characterlookup.py", line 118, in __init__ self.hasComponentLookup = self.db.hasTable('ComponentLookup') File "/usr/local/lib/python2.7/dist-packages/cjklib/dbconnector.py", line 444, in hasTable schema = self._findTable(tableName) File "/usr/local/lib/python2.7/dist-packages/cjklib/dbconnector.py", line 429, in _findTable if hasTable(tableName, schema=schema): File "build/bdist.linux-x86_64/egg/sqlalchemy/engine/base.py", line 2525, in has_table File "build/bdist.linux-x86_64/egg/sqlalchemy/engine/base.py", line 2412, in run_callable File "build/bdist.linux-x86_64/egg/sqlalchemy/engine/base.py", line 1959, in run_callable File "build/bdist.linux-x86_64/egg/sqlalchemy/dialects/sqlite/base.py", line 567, in has_table File "build/bdist.linux-x86_64/egg/sqlalchemy/engine/base.py", line 1450, in execute File "build/bdist.linux-x86_64/egg/sqlalchemy/engine/base.py", line 1627, in _execute_text File "build/bdist.linux-x86_64/egg/sqlalchemy/engine/base.py", line 1697, in _execute_context File "build/bdist.linux-x86_64/egg/sqlalchemy/engine/base.py", line 1690, in _execute_context File "build/bdist.linux-x86_64/egg/sqlalchemy/engine/default.py", line 335, in do_execute sqlalchemy.exc.OperationalError: (OperationalError) unknown database "cjklib_0" 'PRAGMA "cjklib_0".table_info("ComponentLookup")' () If i delete the line I added, it will work as expected again. **Solutions:** How can I make it read both cedict.db and cjklib.db at the same time? I am guessing, only then, it might work for both cases without throwing any errors. Did anyone encounter a similar situation? And how did you solve it? Or, do you have anything else to try out in mind? Just shed some lights please! Thanks in advance! Answer: (1) Your method to make CEDICT work is **not complete**. Although "d = CEDICT()" doesn't raise any error, you will meet an error when you a dictionary function, such as "d.getFor(u'朋友')". You should add an item in the config file: attach = sqlite:////usr/local/share/cjklib/cjklib.db But, this method still gives a "characterlookup" error (as you mentioned). (2) Real solution: create "dbconnection" explicitly for the dictionary. >>> from cjklib.dictionary import CEDICT >>> from cjklib.dbconnector import getDBConnector >>> db = getDBConnector({'sqlalchemy.url': 'sqlite://', 'attach': ['cjklib']}) >>> d=CEDICT(dbConnectInst=db) >>> it=d.getFor(u'朋友') **EDIT:** Keep cjklib.conf with default configuration.
Writing a notification program using Tweepy Question: In trying to learn the Python-tweepy api, I put together a little bit of code that tells me if there has been any new tweets within the most recent ~10 second interval (of course, in practice it is more than 10 seconds because code aside from `sleep(10)` also takes some time to run): from getApi import getApi from time import sleep from datetime import datetime api = getApi() top = api.home_timeline()[0].id while True: l = api.home_timeline() if top != l[0].id: top = l[0].id print 'New tweet recognized by Python at: %s' % str(datetime.now()) sleep(10) getApi is just a few lines of Python I wrote to manage OAuth using tweepy. The getApi method returns the tweepy api, with my account authenticated. It seems very inefficient that I would have to ask twitter again and again whether there are any new tweets. Is this how it is normally done? If not, what would be the 'canonical' way to do it? I would have imagined that there would be some code like: api.set_home_timeline_handler(tweetHandler) and tweetHandler would be called whenever there is a new tweet. Answer: It's the way the twitter API works - you have ask every time you want to know about stuff on twitter. But beware of rate limiting `https://dev.twitter.com/docs/rate-limiting` every 10 sec is above the max. Alternatively there is streaming api: `https://dev.twitter.com/docs/streaming- api/methods` that works like you imagined, but it is for bigger tasks than checking your timeline.
How to play song from Playlist Question: I am making a music player in python 2.6 with Tkinter. Here's my code : from Tkinter import * import mp3play import tkFileDialog import Tkinter def open_file(): #Opens a dialog box to open .mp3 file global music #then sends filename to file_name_label. global mp3 global play_list filename.set (tkFileDialog.askopenfilename(defaultextension = ".mp3", filetypes=[("All Types", ".*"), ("MP3", ".mp3")])) playlist = filename.get() playlist_pieces = playlist.split("/") play_list.set (playlist_pieces[-1]) playl = play_list.get() play_list_display.insert(END, playl) mp3 = filename.get() print mp3 music = mp3play.load(mp3) pieces = mp3.split("/") name.set (pieces[-1]) def play(): #Plays the .mp3 file music.play() def stop(): #Stops the .mp3 file music.stop() def pause(): #Pauses or unpauses the .mp3 file if music.ispaused() == True: music.unpause() elif music.ispaused() == False: music.pause() def vol(event): #Allows volume to be changed with the slider v = Scale.get(volume_slider) music.volume(v) def Exit(): exit() root = Tk() root.title("EmoPlayer") root.geometry('300x100+250+100') filename = Tkinter.StringVar() name = Tkinter.StringVar() play_list = Tkinter.StringVar() menubar = Menu(root) filemenu = Menu(menubar, tearoff=0) menubar.add_cascade(label='File', menu = filemenu) filemenu.add_command(label='Open', command = open_file) filemenu.add_separator() filemenu.add_command(label='Exit', command = Exit) root.config(menu=menubar) open_file = Button(root, width = 6, height = 1, text = 'Open file', command = open_file) open_file.grid(row=0, column=3) play_button = Button(root, width = 5, height = 1, text='Play', command = play) play_button.grid(row=0, column=0, sticky = W) stop_button = Button(root, width = 5, height = 1, text='Stop', command = stop) stop_button.grid(row=0, column=1, sticky = W) pause_button = Button(root, width = 5, height = 1, text='Pause', command = pause) pause_button.grid(row=0, column=2) volume_slider = Scale(root, label='Volume', orient = 'horizontal', fg = 'black', command = vol) volume_slider.grid(row=0, column=4) file_name_label = Label(root, font=('Verdana', 8), fg = 'black', wraplength = 300, textvariable=name ) file_name_label.grid(row=3, column=0, columnspan=8) play_list_window = Toplevel(root, height = 150, width = 100) play_list_window.title("Playlist") play_list_display = Listbox(play_list_window, width = 50) play_list_display.pack() play_list_window.mainloop() root.mainloop() This code can open a mp3 file, insert it in playlist and play it. But it cant allow to play song by selecting it from playlist. Can anyone tell me how to make things work by selecting from playlist? Answer: You can subscribe to either selection changed (`"<<ListboxSelect>>"`) or double click events (`"<Double-Button-1>"`) of your listbox. Note that you will have to store somewhere the complete path of mp3 files (the name of the file as displayed in the playlist is not enough to play it). def tune_changed(event): idx = event.widget.curselection()[0] print ("Now playing %s" % event.widget.get(idx)) play_list_display.bind("<Double-Button-1>", tune_changed) play_list_display.bind("<<ListboxSelect>>", tune_changed)
Python adding text at the line Question: I have a file which contains following row: //hva_SaastonJakaumanMuutos/printData/reallocationAssignment/changeUser/firstName> I want to add "John" at the end of line. I have written following code but for some reason it is not working, def add_text_to_file(self, file, rowTitle, inputText): f = open("check_files/"+file+".txt", "r") fileList = list(f) f.close() j = 0 for row in fileList : if fileList[j].find(rowTitle) > 0 : fileList[j]=fileList[j].replace("\n","")+inputText+"\n" break j = j+1 f = open("check_files/"+file+".txt", "w") f.writelines(fileList) f.close() Do you see where am I doing wrong? Answer: `str.find` may return `0` if the text you are searching is found at the beginning. After all, it returns the index the match begins. So your condition should be: if fileList[j].find(rowTitle) >= 0 : **Edit:** The correction above would save the day but it's better if you things the _right_ way, the pythonic way. * If you are looking for a substring in a text, you can use the `foo in bar` comparison. It will be `True` if `foo` can be found in `bar` and `False` otherwise. * You rarely need a counter in Python. `enumerate` built-in is your friend here. * You can combine the iteration and writing and eliminate an unnecessary step. * `strip` or [`rstrip`](http://docs.python.org/library/stdtypes.html#str.rstrip) is better than replace in your case. * For Python 2.6+, it is better to use `with` statement when dealing with files. It will deal with the closing of the file right way. For Python 2.5, you need `from __future__ import with_statement` * Refer to [PEP8](http://www.python.org/dev/peps/pep-0008/) for commonly preferred naming conventions. Here is a cleaned up version: def add_text_to_file(self, file, row_title, input_text): with open("check_files/" + file + ".txt", "r") as infile: file_list = infile.readlines() with open("check_files/" + file + ".txt", "w") as outfile: for row in file_list: if row_title in row: row = row.rstrip() + input_text + "\n" outfile.write(row)
google-app-engine : Import works only after a refresh Question: After somes problems with a simple import of httplib2 (see my post [here](http://stackoverflow.com/questions/10471111/google-app-engine- importerror-httplib2-in-google-api-python-client-hello- world#comment13527322_10471111 "google-app-engine : ImportError httplib2 in google api python client hello world")), i meet a different problem with the import of gflags. In fact, on dev server, i have an ImportError the first time that I lanch the apps. But, if i refresh the browser, the apps works ! If i looking in logs, i can see : ... ImportError: No module named gflags [App Instance] [0] [dev_appserver.py:2891] INFO "GET / HTTP/1.1" 500 - [App Instance] [0] [py_zipimport.py:148] INFO zipimporter('/usr/lib/python2.5/site-packages/setuptools-0.6c11-py2.5.egg', '') [App Instance] [0] [py_zipimport.py:148] INFO zipimporter('/usr/lib/python2.5/site-packages/python_gflags-2.0-py2.5.egg', '') So, the apps works after a refresh on dev server but it doesn't work at all after an upload on appspot : <type 'exceptions.ImportError'>: No module named gflags Traceback (most recent call last): File "/base/data/home/apps/s~yoyocontacts/2.358733066847060730/main.py", line 33, in <module> from apiclient.discovery import build File "/base/data/home/apps/s~yoyocontacts/2.358733066847060730/apiclient/discovery.py", line 48, in <module> from apiclient.http import HttpRequest File "/base/data/home/apps/s~yoyocontacts/2.358733066847060730/apiclient/http.py", line 47, in <module> from model import JsonModel File "/base/data/home/apps/s~yoyocontacts/2.358733066847060730/apiclient/model.py", line 27, in <module> import gflags My application is this [HelloWorld](http://code.google.com/p/google-api- python-client/source/browse/#hg%2Fsamples%2Fappengine "google-api-python- client Appengine") : lrwxrwxrwx 1 yoyo 77 2012-05-06 16:24 apiclient -> /home/yoyo/dev/outils/google_appengine/lib/google-api-python-client/apiclient/ -rw-r--r-- 1 yoyo 169 2012-05-06 16:19 app.yaml -rw-r--r-- 1 yoyo 358 2012-05-06 15:20 client_secrets.json lrwxrwxrwx 1 yoyo 60 2012-05-07 12:12 gflags -> /home/yoyo/dev/outils/google_appengine/lib/python-gflags/ -rw-r--r-- 1 yoyo 554 2012-03-02 20:00 grant.html lrwxrwxrwx 1 yoyo 60 2012-05-06 16:20 httplib2 -> /home/yoyo/dev/outils/google_appengine/lib/httplib2/httplib2/ -rw-r--r-- 1 yoyo 471 2012-03-02 20:00 index.yaml -rw-r--r-- 1 yoyo 3,4K 2012-05-07 11:45 main.py lrwxrwxrwx 1 yoyo 56 2012-05-06 16:24 oauth2 -> /home/yoyo/dev/outils/google_appengine/lib/oauth2/oauth2/ lrwxrwxrwx 1 yoyo 80 2012-05-07 10:59 oauth2client -> /home/yoyo/dev/outils/google_appengine/lib/google-api-python-client/oauth2client/ -rwxr-xr-x 1 yoyo 163 2012-05-07 11:14 run* -rwxr-xr-x 1 yoyo 115 2012-05-07 11:50 upload* lrwxrwxrwx 1 yoyo 79 2012-05-06 16:24 uritemplate -> /home/yoyo/dev/outils/google_appengine/lib/google-api-python-client/uritemplate/ -rw-r--r-- 1 yoyo 102 2012-03-02 20:00 welcome.html My questions : * Why zipimporter works only after a refresh ? * How fix this error on appspot ? Answer: Thans @greg. I added `__init__.py` with `import gflags` then I modified `apiclient/model.py` with `from gflags import gflags` instead of just `import gflags`.
ZIP folder with subfolder in python Question: I need to zip a folder that containts an .xml file and a .fgdb file by using python. Could anyone help me? I tried a few scripts I found on internet but there is always some technical issue (such as creating an empty zip file, or create zip file I cannot open 'no permission' etc..) Thanks in advance. Answer: The key to making it work is the os.walk() function. Here is a script I assembled in the past that should work. Let me know if you get any exceptions. import zipfile import os import sys def zipfolder(foldername, target_dir): zipobj = zipfile.ZipFile(foldername + '.zip', 'w', zipfile.ZIP_DEFLATED) rootlen = len(target_dir) + 1 for base, dirs, files in os.walk(target_dir): for file in files: fn = os.path.join(base, file) zipobj.write(fn, fn[rootlen:]) zipfolder('thenameofthezipfile', 'thedirectorytobezipped') #insert your variables here sys.exit()
How do I tell py2app to use/include 32bit Python (for wxPython)? Question: I'm using OS X Lion (10.7.3) and I'm trying to write a cross-platform, stand- alone GUI-based program using `wxPython` and `py2app`. I tried to use Python 2.7.1 which comes shipped with Lion. I got the `wxPython2.8` binaries (wxPython2.8-osx-unicode-py2.7). I installed `py2app` via pip. This is my little test app: #!/usr/bin/python import wx app = wx.App() frame = wx.Frame(None, -1, 'test.py') frame.Show() app.MainLoop() This is my `setup.py`: from setuptools import setup setup( app=["test.py"], setup_requires=["py2app"], ) wxPython 2.8 wants 32-bit mode, so I use the `arch` command: arch -i386 /usr/bin/python2.7 test.py **How do I tell py2app to use/include 32bit Python?** It is possible to manually exchange the relevant files in the app bundle, but that's a rather clumsy workaround. I could also use 64bit wxPython2.9, but there isn't a stable release available yet. Should I switch to `cx_Freeze`? What is the best practice here? Answer: If you have 64 bit Python installed, then it will create a 64 bit application. If you have 32 bit Python installed, then it will create a 32 bit application. If you have both installed, then what is created will depend on where Python collects it's libraries from, the 32 bit or 64 bit install folders. On Windows, this depends on which Python executable is actually run. And this depends on which is first in your system or user PATH settings. When you type **python setup.py** , Windows runs **python.exe** which python.exe is run from the command line depends on you **PATH** environemnt variable. Which is run if you douple click **setup.py** in explorer depends on you file associations with **.py** files. You could easily make setup.py ensure the correct is being run by spawning a 32bit python instance from within an arbitrary one.
How to get the directory of an argparse file in Python? Question: I use [`argparse`](http://docs.python.org/library/argparse.html) to get a file from the user: import argparse, os parser = argparse.ArgumentParser() parser.add_argument('file', type=file) args = parser.parse_args() Then I want to know the directory where this file is, something like: print(os.path.abspath(os.path.dirname(args.inputfile))) But of course, as `args.inputfile` is a `file` object, this does not work. How to do it? Answer: You can get the name of the file from the `.name` attribute, and then pass this to `os.path.abspath`. For example: args = parser.parse_args() path = os.path.abspath(args.file.name)
How to handle multi-page images in PythonMagick? Question: I want to convert some multi-pages .tif or .pdf files to individual .png images. From command line (using ImageMagick) I just do: convert multi_page.pdf file_out.png And I get all the pages as individual images (file_out-0.png, file_out-1.png, ...) I would like to handle this file conversion within Python, unfortunately PIL cannot read .pdf files, so I want to use PythonMagick. I tried: import PythonMagick im = PythonMagick.Image('multi_page.pdf') im.write("file_out%d.png") or just im.write("file_out.png") But I only get 1 page converted to png. Of course I could load each pages individually and convert them one by one. But there must be a way to do them all at once? Answer: ImageMagick is not memory efficient, so if you try to read a large pdf, like 100 pages or so, the memory requirement will be huge and it might crash or seriously slow down your system. So after all reading all pages at once with PythonMagick is a bad idea, its not safe. So for pdfs, I ended up doing it page by page, but for that I need to get the number of pages first using pyPdf, its reasonably fast: pdf_im = pyPdf.PdfFileReader(file('multi_page.pdf', "rb")) npage = pdf_im.getNumPages() for p in npage: im = PythonMagick.Image('multi_page.pdf['+ str(p) +']') im.write('file_out-' + str(p)+ '.png')
cache in python function Question: This appeared as some test question. If you consider this function which uses a cache argument as the 1st argument def f(cache, key, val): cache[key] = val # insert some insanely complicated operation on the cache print cache and now create a dictionary and use the function like so: c = {} f(c,"one",1) f(c,"two",2) this seems to work as expected (i.e adding to the c dictionary), but is it actually passing that reference or is it doing some inefficient copy ? Answer: The dictionary passed to cache is not copied. As long as the `cache` variable is not **rebound** inside the function, it stays the same object, and modifications to the dictionary it refers to will affect the dictionary outside. There is not even any need to return `cache` in this case (and indeed the sample code does not). It might be better if `f` was a method on a dictionary-like object, to make this more conceptually clear. If you use the `id()` function (built-in, does not need to be imported) you can get a unique identifier for any object. You can use that to confirm that you are really and truly dealing with the same object and not any sort of copy.
'Document' object has no attribute 'get_uri' Question: I'm working on porting some Gedit 2 plugins to Gedit 3 and I've run into the error `'Document' object has no attribute 'get_uri'` and am stumped as to what's wrong. For what it's worth, the Gedit 2 version of the plugin works. def view_result(self, widget): # Get the selection object tree_selection = self.results_list.get_selection() # Get the model and iterator for the row selected (model, iterator) = tree_selection.get_selected() if (iterator): # Get the absolute path of the file absolute_path = model.get_value(iterator, 3) # Get the line number line_number = int(model.get_value(iterator, 2)) - 1 # Get all open tabs documents = self.window.get_documents() # Loop through the tabs until we find which one matches the file # If we don't find it, we'll create it in a new tab afterwards. for each in documents: # This is the line throwing the error: if (each.get_uri().replace("file://", "") == absolute_path): # This sets the active tab to "each" (self.window.set_active_tab (Gedit.tab_get_from_document(each))) each.goto_line(line_number) # Get the bounds of the document (start, end) = each.get_bounds() self.window.get_active_view().scroll_to_iter(end, 0.0) x = each.get_iter_at_line_offset(line_number, 0) self.window.get_active_view().scroll_to_iter(x, 0.0) return # If we got this far, then we didn't find the file open in a tab. # Thus, we'll want to go ahead and open it... self.window.create_tab_from_uri("file://" + absolute_path, self.encoding, int(model.get_value(iterator, 2)), False, True) Additionally, I have the following import lines in my file: from gi.repository import Gtk, Gio, GObject, Gedit import os I've tried looking in the Gedit 3 plugins that I already have for a similar line to see if something changed, but they have the same type of code, and neither searching Google nor StackOverflow have given me anything I can work with. I'm new to Python and doing this to learn it, so I could be missing something totally obvious, but what is it? **Edit** `print each, type(each), dir(each)` produces the following: <Document object at 0x20ea3c0 (GeditDocument at 0x21d2030)> <class 'gi.repository.Gedit.Document'> ['__class__', '__copy__', '__deepcopy__', '__delattr__', '__dict__', '__doc__', '__eq__', '__format__', '__gdoc__', '__ge__', '__getattribute__', '__grefcount__', '__gt__', '__gtype__', '__hash__', '__info__', '__init__', '__le__', '__lt__', '__module__', '__ne__', '__new__', '__reduce__', '__reduce_ex__', '__repr__', '__setattr__', '__sizeof__', '__str__', '__subclasshook__', '_get_or_create_tag_table', 'add_mark', 'add_selection_clipboard', 'apply_tag', 'apply_tag_by_name', 'backspace', 'backward_iter_to_source_mark', 'begin_not_undoable_action', 'begin_user_action', 'buffer', 'can_redo', 'can_undo', 'chain', 'connect', 'connect_after', 'connect_object', 'connect_object_after', 'copy_clipboard', 'create_child_anchor', 'create_mark', 'create_source_mark', 'create_tag', 'cut_clipboard', 'delete', 'delete_interactive', 'delete_mark', 'delete_mark_by_name', 'delete_selection', 'deserialize', 'deserialize_get_can_create_tags', 'deserialize_set_can_create_tags', 'disconnect', 'disconnect_by_func', 'do_apply_tag', 'do_begin_user_action', 'do_bracket_matched', 'do_changed', 'do_cursor_moved', 'do_delete_range', 'do_end_user_action', 'do_insert_child_anchor', 'do_insert_pixbuf', 'do_insert_text', 'do_load', 'do_loaded', 'do_loading', 'do_mark_deleted', 'do_mark_set', 'do_modified_changed', 'do_paste_done', 'do_redo', 'do_remove_tag', 'do_save', 'do_saved', 'do_saving', 'do_search_highlight_updated', 'do_undo', 'emit', 'emit_stop_by_name', 'end_not_undoable_action', 'end_user_action', 'ensure_highlight', 'error_quark', 'forward_iter_to_source_mark', 'freeze_notify', 'get_bounds', 'get_can_search_again', 'get_char_count', 'get_compression_type', 'get_content_type', 'get_context_classes_at_iter', 'get_copy_target_list', 'get_data', 'get_deleted', 'get_deserialize_formats', 'get_enable_search_highlighting', 'get_encoding', 'get_end_iter', 'get_has_selection', 'get_highlight_matching_brackets', 'get_highlight_syntax', 'get_insert', 'get_iter_at_child_anchor', 'get_iter_at_line', 'get_iter_at_line_index', 'get_iter_at_line_offset', 'get_iter_at_mark', 'get_iter_at_offset', 'get_language', 'get_line_count', 'get_location', 'get_mark', 'get_max_undo_levels', 'get_metadata', 'get_mime_type', 'get_modified', 'get_newline_type', 'get_paste_target_list', 'get_properties', 'get_property', 'get_readonly', 'get_search_text', 'get_selection_bound', 'get_selection_bounds', 'get_serialize_formats', 'get_short_name_for_display', 'get_slice', 'get_source_marks_at_iter', 'get_source_marks_at_line', 'get_start_iter', 'get_style_scheme', 'get_tag_table', 'get_text', 'get_undo_manager', 'get_uri_for_display', 'goto_line', 'goto_line_offset', 'handler_block', 'handler_block_by_func', 'handler_disconnect', 'handler_is_connected', 'handler_unblock', 'handler_unblock_by_func', 'insert', 'insert_at_cursor', 'insert_child_anchor', 'insert_interactive', 'insert_interactive_at_cursor', 'insert_pixbuf', 'insert_range', 'insert_range_interactive', 'insert_with_tags', 'insert_with_tags_by_name', 'is_local', 'is_untitled', 'is_untouched', 'iter_backward_to_context_class_toggle', 'iter_forward_to_context_class_toggle', 'iter_has_context_class', 'load', 'load_cancel', 'load_stream', 'move_mark', 'move_mark_by_name', 'new', 'new_with_language', 'notify', 'parent_instance', 'paste_clipboard', 'place_cursor', 'priv', 'props', 'redo', 'register_deserialize_format', 'register_deserialize_tagset', 'register_serialize_format', 'register_serialize_tagset', 'remove_all_tags', 'remove_selection_clipboard', 'remove_source_marks', 'remove_tag', 'remove_tag_by_name', 'replace_all', 'save', 'save_as', 'search_backward', 'search_forward', 'select_range', 'serialize', 'set_content_type', 'set_data', 'set_enable_search_highlighting', 'set_highlight_matching_brackets', 'set_highlight_syntax', 'set_language', 'set_location', 'set_max_undo_levels', 'set_modified', 'set_properties', 'set_property', 'set_search_text', 'set_short_name_for_display', 'set_style_scheme', 'set_text', 'set_undo_manager', 'stop_emission', 'thaw_notify', 'undo', 'unregister_deserialize_format', 'unregister_serialize_format', 'weak_ref'] Answer: As I suspected, it was something simple. They changed `Gedit.Document.get_uri()` to `Gedit.Document.get_location()` or `Gedit.Document.get_uri_for_display()` (depending on your purposes). For others who may be having issues finding the docs for Gedit, here they are - <http://developer.gnome.org/gedit/>
Python and gevent - AttributeError: 'module' object has no attribute 'queue' Question: I am rather new with gevent but I an trying to create a queue but I get the below error. I am using python2.7. import gevent queue = gevent.queue.Queue() Traceback (most recent call last): File "/home/ubuntu/workspace/rtbopsConfig/rtbServers/rtbAsyncServers/bottleServer.py", line 8, in <module> queue = gevent.queue.Queue() AttributeError: 'module' object has no attribute 'queue' Answer: Try: import gevent.queue queue = gevent.queue.Queue() Or from gevent.queue import Queue queue = Queue()
Serial communication Python to Arduino - can't recognise carriage return Question: I'm trying to communicate via serial between a BeagleBone running Ubuntu 10.04 and an Arduino. So far, I can send a string okay, but I'm having problems recognising the newline character. From the BB side, in Python3 and using PySerial, I have (edited for just the relevant bits): import serial ser = serial.Serial('/dev/ttyACM0', 9600) ser.write(chr(13).encode('ascii')) # establishes serial connection # which will reset Arduino delay(3000) # give time for reset. This method is from my own library mesg = 'Beagle\n' ser.write(mesg.encode('ascii')) On the Arduino side I have: boolean newMsg = false; String incomingMsg = ""; void setup() { /* some stuff - not relevant */ Serial.begin(9600); } void loop() { if(newMsg) { lcd.print(incomingMsg); newMsg = false; } } void serialEvent() { incomingMsg = ""; while (Serial.available() > 0) { char inByte = Serial.read(); if (inByte == '\n') { newMsg = true; } else { incomingMsg = incomingMsg + inByte; } } } The problem is that newMsg never gets set to true because the `if (inByte == '\n')` never gets validated as true. I'even tried using '\r' on both sides and even a type-able character ('#'), but this test never works. The string 'Beagle' makes it through fine, though, so `incomingMsg` builds up okay. Weirdly, I have this working between an Arduino and Processing (the Arduino on a robot connecting to Processing on a laptop via Bluetooth). I just can't see why it isn't working here. Any thoughts? **UPDATE** : I have a partial answer, and one that will work for now, although I'd still like to know what's broken. The `if (inByte == '\n')` is getting validated as true. But for some reason, the assignment of true to the global boolean var `newMsg` isn't working. Despite the assignment in serialEvent(), its value remains resolutely false inside loop(). Yet it's a global var (which, despite most programmers' aversion to them, are used quite a bit with the Arduino). I replaced the test in loop() with: if (messageReceived != "") and now it works. But I'd still like to know why that boolean problem exists. Answer: Since newMsg is being changed in an interrupt driven function you may need to declare newMsg as volatile: volatile boolean newMsg = false; The will inform the compiler that the value may change and it should not optimize it. [Arduino Volatile reference](http://arduino.cc/en/Reference/Volatile)
"Bad marshal data" Django development server error Question: Got this error while insterting data into my MySQL database ValueError at /admin/arbkdb/arbkcompany/ bad marshal data (unknown type code) Request Method: GET Request URL: http://[2001:6f8:1c00:18b::2]:9000/admin/arbkdb/arbkcompany/ Django Version: 1.3 Exception Type: ValueError Exception Value: bad marshal data (unknown type code) Exception Location: /usr/lib/python2.7/dist-packages/simplejson/__init__.py in <module>, line 111 Python Executable: /usr/bin/python Python Version: 2.7.2 Python Path: ['/home/ardian/.experiments/arbk', '/usr/lib/python2.7', '/usr/lib/python2.7/plat-linux2', '/usr/lib/python2.7/lib-tk', '/usr/lib/python2.7/lib-old', '/usr/lib/python2.7/lib-dynload', '/usr/local/lib/python2.7/dist-packages', '/usr/lib/python2.7/dist-packages', '/usr/lib/python2.7/dist-packages/PIL', '/usr/lib/python2.7/dist-packages/gst-0.10', '/usr/lib/python2.7/dist-packages/gtk-2.0', '/usr/lib/pymodules/python2.7', '/usr/lib/python2.7/dist-packages/ubuntu-sso-client', '/usr/lib/python2.7/dist-packages/ubuntuone-client', '/usr/lib/python2.7/dist-packages/ubuntuone-control-panel', '/usr/lib/python2.7/dist-packages/ubuntuone-couch', '/usr/lib/python2.7/dist-packages/ubuntuone-installer', '/usr/lib/python2.7/dist-packages/ubuntuone-storage-protocol'] Server time: Tue, 8 May 2012 16:15:19 -050 # Trackback Environment: Request Method: GET Request URL: http://[2001:6f8:1c00:18b::2]:9000/admin/arbkdb/arbkcompany/ Django Version: 1.3 Python Version: 2.7.2 Installed Applications: ['admin_tools', 'admin_tools.theming', 'admin_tools.menu', 'admin_tools.dashboard', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.sites', 'django.contrib.messages', 'django.contrib.staticfiles', 'arbkdb', 'south', 'django.contrib.admin'] Installed Middleware: ('django.middleware.common.CommonMiddleware', 'django.contrib.sessions.middleware.SessionMiddleware', 'django.middleware.csrf.CsrfViewMiddleware', 'django.contrib.auth.middleware.AuthenticationMiddleware', 'django.contrib.messages.middleware.MessageMiddleware') Traceback: File "/usr/lib/pymodules/python2.7/django/core/handlers/base.py" in get_response 89. response = middleware_method(request) File "/usr/lib/pymodules/python2.7/django/contrib/messages/middleware.py" in process_request 11. request._messages = default_storage(request) File "/usr/lib/pymodules/python2.7/django/contrib/messages/storage/__init__.py" in <lambda> 31. default_storage = lambda request: get_storage(settings.MESSAGE_STORAGE)(request) File "/usr/lib/pymodules/python2.7/django/contrib/messages/storage/__init__.py" in get_storage 17. mod = import_module(module) File "/usr/lib/pymodules/python2.7/django/utils/importlib.py" in import_module 35. __import__(name) File "/usr/lib/pymodules/python2.7/django/contrib/messages/storage/user_messages.py" in <module> 8. from django.contrib.messages.storage.fallback import FallbackStorage File "/usr/lib/pymodules/python2.7/django/contrib/messages/storage/fallback.py" in <module> 2. from django.contrib.messages.storage.cookie import CookieStorage File "/usr/lib/pymodules/python2.7/django/contrib/messages/storage/cookie.py" in <module> 5. from django.utils import simplejson as json File "/usr/lib/pymodules/python2.7/django/utils/simplejson/__init__.py" in <module> 111. import simplejson File "/usr/lib/python2.7/dist-packages/simplejson/__init__.py" in <module> 111. from decoder import JSONDecoder, JSONDecodeError Exception Type: ValueError at /admin/arbkdb/arbkcompany/ Exception Value: bad marshal data (unknown type code) Ps. I am not sure how to describe why it came to this error because it appeard while inserting a lot of data and I don't know why This is my model data <https://github.com/ardian/arbk/blob/master/arbkdb/models.py> Answer: Looks like is not a database problem but a corrupted files message. Removing *.pyc and *.pyo files solves this.
Python - Installing matplotlib in Mac OSX Snow Leopard Question: I've been having trouble installing matplotlib. I'm getting a similar error to many other topics, but none of those solutions have been working for me. I have tried installing matplotlib via pip and via git and I receive the same error every time I would very much appreciate help. In file included from src/ft2font.cpp:3: src/ft2font.h:16:22: error: ft2build.h: No such file or directory src/ft2font.h:17:10: error: #include expects "FILENAME" or <FILENAME> src/ft2font.h:18:10: error: #include expects "FILENAME" or <FILENAME> src/ft2font.h:19:10: error: #include expects "FILENAME" or <FILENAME> src/ft2font.h:20:10: error: #include expects "FILENAME" or <FILENAME> src/ft2font.h:21:10: error: #include expects "FILENAME" or <FILENAME> In file included from src/ft2font.cpp:3: src/ft2font.h:34: error: 'FT_Bitmap' has not been declared src/ft2font.h:34: error: 'FT_Int' has not been declared src/ft2font.h:34: error: 'FT_Int' has not been declared src/ft2font.h:86: error: expected ',' or '...' before '&' token src/ft2font.h:86: error: ISO C++ forbids declaration of 'FT_Face' with no type src/ft2font.h:132: error: 'FT_Face' does not name a type src/ft2font.h:133: error: 'FT_Matrix' does not name a type src/ft2font.h:134: error: 'FT_Vector' does not name a type src/ft2font.h:135: error: 'FT_Error' does not name a type src/ft2font.h:136: error: 'FT_Glyph' was not declared in this scope src/ft2font.h:136: error: template argument 1 is invalid src/ft2font.h:136: error: template argument 2 is invalid src/ft2font.h:137: error: 'FT_Vector' was not declared in this scope src/ft2font.h:137: error: template argument 1 is invalid src/ft2font.h:137: error: template argument 2 is invalid src/ft2font.h:143: error: 'FT_BBox' does not name a type src/ft2font.cpp:41: error: 'FT_Library' does not name a type src/ft2font.cpp:106: error: variable or field 'draw_bitmap' declared void src/ft2font.cpp:106: error: 'FT_Bitmap' was not declared in this scope src/ft2font.cpp:106: error: 'bitmap' was not declared in this scope src/ft2font.cpp:107: error: 'FT_Int' was not declared in this scope src/ft2font.cpp:108: error: 'FT_Int' was not declared in this scope /opt/local/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/site-packages/numpy/core/include/numpy/__multiarray_api.h:1532: warning: 'int _import_array()' defined but not used error: command '/usr/bin/gcc-4.2' failed with exit status 1 Answer: I had the same problem. I use brew. I fixed this by doing brew install freetype brew link freetype brew install libpng brew link libpng brew install matplotlib By default, brew leaves your system versions of freetype and libpng active, which is why you need to do "brew link" as well. Hope that helps. Update: I would now recommend using the free version of Anaconda Python. Then this is trivial.
Get IP Mask from IP Address and Mask Length in Python Question: Given an IP Address in dotted quad notation, for example: 192.192.45.1 And a mask length for example 8, 16, 24 typically, but could be anything i.e. 17. Can somebody please provide the code in python to calculate the subnet mask? Preferably I could get the result as 32-bit integer so that it is easy to hash and then reinterpret as dotted quad when necessary for printing. I see that python has a socket library which is basically a wrapper around the unix socket api. I also saw it has the function inet_ntoa(), but it returns some sort of packet struct. I'm not terribly familiar with the Python struct library, so I was hoping some other would have some ideas. Thanks! Answer: The simplest way is to use google's [ipaddr](https://github.com/google/ipaddr- py) module. I assume a 25 bit mask below, but as you say, it could be anything >>> import ipaddr >>> mask = ipaddr.IPv4Network('192.192.45.1/25') >>> mask.netmask IPv4Address('255.255.255.128') >>> The module is rather efficient at manipulating IPv4 and IPv6 addresses... a sample of some other functionality in it... >>> ## Subnet number? >>> mask.network IPv4Address('192.192.45.0') >>> >>> ## RFC 1918 space? >>> mask.is_private False >>> >> ## The subnet broadcast address >>> mask.broadcast IPv4Address('192.192.45.127') >>> mask.iterhosts() <generator object iterhosts at 0xb72b3f2c>
Difference between PyMODINIT_FUNC and PyModule_Create Question: If I'm understanding correctly, (a) PyMODINIT_FUNC in Python 2.X has been replaced by PyModule_Create in Python3.X (b) Both return PyObject*, however, in Python 3.X, the module's initialization function _MUST_ return the PyObject* to the module - i.e. PyMODINIT_FUNC PyInit_spam(void) { return PyModule_Create(&spammodule); } whereas in Python2.X, this is not necessary - i.e. PyMODINIT_FUNC initspam(void) { (void) Py_InitModule("spam", SpamMethods); } So, my sanity checking questions are: (1) Is my understanding correct? (2) Why was this change made? Right now, I'm only experimenting with very simple cases of C-extensions of Python. Perhaps if I were doing more, the answer to this would be obvious, or maybe if I were trying to embed Python into something else.... Answer: 1. Yes, your understanding is correct. You must return the new module object from the initing function with return type PyMODINIT_FUNC. (PyMODINIT_FUNC declares the function to return void in python2, and to return PyObject* in python3.) 2. I can only speculate as to the motivations of the people who made the change, but I believe it was so that errors in importing the module could be more easily identified (you can return NULL from the module-init function in python3 if something went wrong).
Deploying django - "ImportError" for Apache VirtualHost and mod_wsgi Question: I'm deploying django on port 81 of my webserver. This is to get it off the development server, but I'm not ready to have it be served as the root on port 80. The problem is that any time I try to access any page on port 81, I see the django error screen and it always says: `ImportError at / No module named mysite.urls` ## httpd.conf Listen 81 NameVirtualHost *:81 <VirtualHost *:81> DocumentRoot /home/bill/Desktop/mysite WSGIScriptAlias / /home/bill/Desktop/mysite/django.wsgi <Directory /home/bill/Desktop/mysite> Order allow,deny Allow from all </Directory> </VirtualHost> ## /home/bill/Desktop/mysite/django.wsgi import os import sys sys.path.append('/home/bill/Desktop/mysite') os.environ['PYTHON_EGG_CACHE'] = '/home/bill/Desktop/mysite/.python-egg' os.environ['DJANGO_SETTINGS_MODULE'] = 'settings' import django.core.handlers.wsgi application = django.core.handlers.wsgi.WSGIHandler() ## in mysite/settings.py ... ROOT_URLCONF = 'mysite.urls' ... I know for a fact that `ROOT_URLCONF = 'mysite.urls'` is getting loaded, because if I change it to anything else (like "test"), I get `ImportError at / No module named test` Any thoughts about where this deployment has gone wrong? Thanks in advance! Answer: Your deployment is fine. Your code needs to be corrected, in that it should only be importing (and subsequently using) `urls`. (Although `os.environ['DJANGO_SETTINGS_MODULE'] = 'settings'` is sort of redundant.)
VS2010, C#, Python: Python script file execution on runtime Question: I wish to create a sample program in C# where it downloaded real time data (ie datalogger) via USB port. C# accept the data (hex or numerical) and then automatically download a python file (ie validatemethodA.ps) which is then executed. The python accept the data from the C# code and then do validation check on data or do complex calculation and return results back to C#, where the data is displayed on window form and appended to the file (by C#). The Python is a script, where it does not requires complies in advance (during c# runtime) this mean the user is free to modify the python script to optimise pass/fails parameter or calculation results without getting back to VS2010 to complies the whole program. This mean I can supply release C# product and only user can modify the python file. How this is achieved?, is there sample/demo, can anyone link me to this solution so I can experiment this proof of concept? Answer: There are a couple of ways to do this...one would be to "shell out" to Python by invoking a system call from your C# program. There, you would be looking to use the .NET runtime Process.Start method to run the Python interpreter as a subprocess from your C# program. Another option would be to use a tighter integration between C# and Python by using the [IronPython interpreter](http://ironpython.codeplex.com/). IronPython (ipy), is the python interpreter implemented in .NET ipy can run Python code (essentially the same as normal "c" python, but with some differences), but can also import .NET assemblies and interact with the .NET runtime, directly.
Python: Failed to import extension - Errno 2 Question: I am having weird behaviors in my Python environment on Mac OS X Lion. Apps like Sublime Text (based on Python) don't work (I initially thought it was an app bug), and now, after I installed hg-git, I get the following error every time I lauch HG in term: `*** failed to import extension hggit from /Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/site- package/hggit/: [Errno 2] No such file or directory` So it probably is a Python environment set up error. Libraries and packages are there in place. Any idea how to fix it? Notes: * I installed hg-git following hg-git web site directions. * I also added the exact path to the extension in my .hgrc file as: `hggit = /Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/site-package/hggit/` * Python was installed using official package on Python web site. * Echoing `$PYTHONPATH` in term print anything Answer: "site-package"? Did you mean "site-packages"?
Python: Access/Save memory block just given by pointer without copying Question: Here is an example of what I try to do: import ctypes MEM_SIZE = 1024*1024*128 # allocate memory (this is Windows specific) ptr = ctypes.cdll.msvcrt.malloc(MEM_SIZE) # make memory accessible to Python calls mem = ctypes.string_at(ptr, MEM_SIZE) # BAD: string_at duplicates memory # store it to disk open(r'test.raw', 'wb').write(mem) In a nutshell: I have a plain memory pointer, I know the size of the block and want to store it on disk or reuse it as a numpy array. How can I do that without generating a copy of the memory block? * * * Related question: [stackoverflow: Fill python ctypes pointer](http://stackoverflow.com/questions/10730841/fill-python-ctypes- pointer) (thanks to Brian Larsen for the hint) Answer: ctypes_array = (ctypes.c_char * MEM_SIZE).from_address(ptr) with open('test.raw', 'wb') as f: f.write(ctypes_array) numpy_array = numpy.frombuffer(ctypes_array, dtype=numpy.byte) numpy_array.tofile('test.raw')
python trick needed to convert dictionary of functions into dictionary of results Question: I am currently blank on how to do this in an effective way.I thought about using objects but I don't see how they could help in this case. Any ideas? from random import choice from copy import deepcopy def main(): def rand_int(): return choice(['yes', 'no']) # any nesting, functions possible spec = { 'answer': rand_int, 'next': {'answer': rand_int}, 'the_answer': 42 } #### looking for elegant (automatic) way to do this result = deepcopy(spec) result['answer'] = result['answer']() result['next']['answer'] = result['next']['answer']() #### until here # result2 = ... print 'result: %s' % result if __name__ == '__main__': main() please do not tell me to use xsd! Answer: You can do this with one line in a [dictionary comprehension](https://www.youtube.com/watch?v=t85uBptTDYY): {key: function() for key, function in mydictionary.items()} Of course, this will throw errors when a value isn't a function, so if that is a possibility, we can simply add a check with [the `callable()` builtin](http://docs.python.org/library/functions.html#callable): {key: (function() if callable(function) else function) for key, function in mydictionary.items()} We then need to deal with the fact that your answer needs to be recursive, this makes it a little more complex, but not too hard to fix: def call_all_callables_in_dict(mapping): if hasattr(mapping, "items"): return {key: call_all_callables_in_dict(value) for key, value in mapping.items()} elif callable(mapping): return mapping() else: return mapping Note that if you have objects with an `items` attribute or method you wish to store in a `dict` this function will be run on, this could cause problems. I would recommend changing the name of that attribute or method, or replacing the check with `isinstance(dict)`. I would also like to note that for misleading function names `rand_int` that returns a string of `'yes'` or `'no'` is probably about as bad as it gets. Generally you want `True`/`False` in those situations as well. As noted in the comments, pre-Python 2.7, you may not have dictionary comprehensions. To get around this, `dict()` will take a generator of tuples, so you can replace a dict comprehension like so: {x: y for x, y in something.items()} With: dict((x, y) for x, y in something.items()) * * * So, in full: from random import choice def rand_int(): return choice(['yes', 'no']) spec = { 'answer': rand_int, 'next': {'answer': rand_int}, 'the_answer': 42 } def call_all_callables_in_dict(mapping): if hasattr(mapping, "items"): return {key: call_all_callables_in_dict(value) for key, value in mapping.items()} elif callable(mapping): return mapping() else: return mapping print(call_all_callables_in_dict(spec)) Gives us: {'answer': 'no', 'the_answer': 42, 'next': {'answer': 'yes'}}
Tkinter canvas updating speed reduces during the course of a program Question: The following python program creates a Tkinter `Canvas` object and draws random matrix on it. It also measures the time it takes to make 10 subsequent updates. As you may see from the output below, this time grows continiously and substantially during the course of the program. What is the reason for this behavior and how can I fix it? from Tkinter import Tk, Canvas import time import numpy as np window = Tk() nRows = 30 nCols = 30 CELL_SIZE = 10 canvas = Canvas(window, width=CELL_SIZE*nRows, height=CELL_SIZE*nCols) canvas.pack() def drawbox(m): for y in range(nRows): for x in range(nCols): if m[y][x]: color = '#00FF00' else: color = '#000000' canvas.create_rectangle(CELL_SIZE*x, CELL_SIZE*y, CELL_SIZE*x+CELL_SIZE, CELL_SIZE*y+CELL_SIZE, fill=color, outline="#000000", width=1) count = 0 timeStart = time.time() while(True): board = np.random.rand(nRows, nCols) > 0.5 if count % 10 == 0: print '%.1f seconds'%(time.time() - timeStart) timeStart = time.time() count = 0 count += 1 drawbox(board) canvas.after(5) canvas.update() Here is the output 0.0 seconds 1.7 seconds 4.1 seconds 6.3 seconds 8.7 seconds Answer: Every time `drawbox` is called in your program, you're creating a new set of rectangles and then drawing them on top of the old rectangles. As time goes on, you're drawing more and more rectangles (even though it doesn't look like it since the new rectangles are being drawn above the old ones). Also note that with the way your program is written, you're bleeding memory. The way to fix this is to create the rectangles on the first go-around and then update them on the subsequent passes using `canvas.itemconfig(rectangle_id,fill=color)`. I've posted an (ugly) modification to your `drawbox` below which accomplishes this. def drawbox(m,_rectangles={}): if(_rectangles): myrectangles=_rectangles else: myrectangles={} for y in range(nRows): for x in range(nCols): if m[y][x]: color = '#00FF00' else: color = '#000000' if(not _rectangles): cid=canvas.create_rectangle(CELL_SIZE*x, CELL_SIZE*y, CELL_SIZE*x+CELL_SIZE, CELL_SIZE*y+CELL_SIZE, fill=color, outline="#000000", width=1) myrectangles[(y,x)]=cid else: canvas.itemconfig(_rectangles[(y,x)],fill=color) if(not _rectangles): _rectangles.update(myrectangles)
Is there a __enter__ and __exit__ equivalent for all functions in a class? Question: One functionality of python that I found very handy when working with databases (or files) are the `__enter__` and `__exit__` functions you can give to a class. Now by using the `with` statement you can make sure that in this block `__enter__` is first called (and you can open the database or file) and after it's done `__exit__` is called (and you can close a database or file. I want to open and close a sqlite transaction every time a function from my Database class is called. I can do it at the start and end of every function, but since it has to be done for every function is that class, I was wondering, are there methods that get called before and after each function call? Like SetUp and TearDown in unittesting. Answer: You can decorate every member function with a pie decorator, something like @transaction def insertData(self): # code and transaction is a decorator you define to wrap the function with a pre and post. Yes, you have to do it for every function. Here is an example def transaction(f): def pre(): print "pre transaction" def post(): print "post transaction" def wrapped(*args): pre() f(*args) post() return wrapped class Foo(object): def __init__(self): print "instantiating" def doFoo(self): print "doing foo" @transaction def doBar(self, value): print "doing bar "+str(value) @transaction def foofunc(): print "hello" foofunc() f=Foo() f.doFoo() f.doBar(5) . stefanos-imac:python borini$ python decorator.py pre transaction hello post transaction instantiating doing foo pre transaction doing bar 5 post transaction The alternative is that you use a metaclass, like this: import types class DecoratedMetaClass(type): def __new__(meta, classname, bases, classDict): def pre(): print "pre transaction" def post(): print "post transaction" newClassDict={} for attributeName, attribute in classDict.items(): if type(attribute) == types.FunctionType: def wrapFunc(f): def wrapper(*args): pre() f(*args) post() return wrapper newAttribute = wrapFunc(attribute) else: newAttribute = attribute newClassDict[attributeName] = newAttribute return type.__new__(meta, classname, bases, newClassDict) class MyClass(object): __metaclass__ = DecoratedMetaClass def __init__(self): print "init" def doBar(self, value): print "doing bar "+str(value) def doFoo(self): print "doing foo" c = MyClass() c.doFoo() c.doBar(4) This is pure black magic, but it works stefanos-imac:python borini$ python metaclass.py pre transaction init post transaction pre transaction doing foo post transaction pre transaction doing bar 4 post transaction You normally don't want to decorate the `__init__`, and you may want to decorate only those methods with a special name, so you may want to replace for attributeName, attribute in classDict.items(): if type(attribute) == types.FunctionType: with something like for attributeName, attribute in classDict.items(): if type(attribute) == types.FunctionType and "trans_" in attributeName[0:6]: This way, only methods called trans_whatever will be transactioned.
App Engine 401/403 Status Codes Not Working on WebApp2 Question: I am trying to raise a 401/403 status for when a user attempts to access something they don't have privileges to. I used the [Webapp2 Exceptions](http://webapp-improved.appspot.com/guide/exceptions.html) example which generates the proper error codes for 404/500 "natural" events. Such as going to <http://localhost:8080/nourl> generates the proper 404 and messing up code generates a 500. But when I use the method such as below to set the code using self.error(XXX) I see the code in the console but it does not show up in the browser. EG If you leave self.error() empty it generates the proper 500 code. If you use self.error(500) the console outputs: INFO 2012-05-09 18:25:29,549 dev_appserver.py:2891] "GET / HTTP/1.1" 500 - But the browser is completely blank. Below is an example app that exhibits this behaviour. Simply change the self.error() line to the desired code and run. The expected result would be that it generates the proper response to the browser based on the code supplied, not just when a "natural" event occurs such as 404. main.py import webapp2 import wsgiref.handlers import logging from google.appengine.api import users class HomeHandler(webapp2.RequestHandler): def get(self): user = users.get_current_user() if user: self.response.out.write("Hi :1", user.nickname) else: self.error(401) app = webapp2.WSGIApplication([ (r'/', HomeHandler), ], debug=True) def handle_401(request, response, exception): logging.exception(exception) response.write("401 Error") response.set_status(401) def handle_403(request, response, exception): logging.exception(exception) response.write("403 Error") response.set_status(403) def handle_404(request, response, exception): logging.exception(exception) response.write("404 Error") response.set_status(404) def handle_500(request, response, exception): logging.exception(exception) response.write("500 Error") response.set_status(500) app.error_handlers[401] = handle_401 app.error_handlers[403] = handle_403 app.error_handlers[404] = handle_404 app.error_handlers[500] = handle_500 # Run the application def main(): app.run() app.yaml application: 401test version: 1 runtime: python27 api_version: 1 threadsafe: yes libraries: - name: webapp2 version: latest handlers: - url: /.* script: main.app Answer: ~~you are using py27 with threadsafe environment. in app.yaml you set`script: main.app` so the code after app is defined is not executed. didn't test it but this should work: # create a bare app bare_app = webapp2.WSGIApplication(debug=True) #define the error handlers def handle_401(request, response, exception): logging.exception(exception) response.write("401 Error") response.set_status(401) def handle_403(request, response, exception): logging.exception(exception) response.write("403 Error") response.set_status(403) def handle_404(request, response, exception): logging.exception(exception) response.write("404 Error") response.set_status(404) def handle_500(request, response, exception): logging.exception(exception) response.write("500 Error") response.set_status(500) # add the error handlers bare_app.error_handlers[401] = handle_401 bare_app.error_handlers[403] = handle_403 bare_app.error_handlers[404] = handle_404 bare_app.error_handlers[500] = handle_500 bare_app.router.add((r'/', HomeHandler)) app = bare_app ~~ **edit** : use self.abort() instead of self.error() <http://webapp-improved.appspot.com/guide/exceptions.html#abort> you can see the difference in the source code: <http://code.google.com/p/webapp-improved/source/browse/webapp2.py#574> while self.error() sets the status code but clears the response, self.abort() executes the function that takes care of the error handling.
Best approach to doing analysis of sets of tags? Question: I have thousands of survey responses that have been tagged according to the content of the response. Each response can have one tag or many (up to 20), and the tags are independent of one another rather than being structured into category-subcategory or something. I want to be able to do analysis like the following: * How many instances of a given tag are there? * Which tags occur most frequently overall? * Where tag X is present, which other tags appear along with it most frequently? * List of all tags with the count of each next to it * Select subsets of the data to do similar analysis on (by country, for example) The people I'm working with have traditionally tackled everything in Excel (general business strategy consulting work), and that won't work in this case. Their response is to change the project framework to something that Excel can handle in a pivot table, but it would be so much better if we could use more robust tools that allow for more sophisticated relationships. I've been learning SQLite but am starting to fear that the kinds of things I want to do will be pretty complicated. I've also been learning Python (for unrelated reasons) and am kind of wondering if an ORM tool and some Python code might be the better way to go. And then there's something like Access (which I don't have but would possibly be willing to get if it's a sweet spot for this kind of thing). In summary, I'd love to know how hard these kinds of analysis would be to do overall and which tools would best be suited for the job. I'm completely open to the idea that I'm thinking about some of or all of the problem in a way that's backwards and would welcome any advice on any aspect of what I've written here. Answer: Collect all tags into a list and use the python collections.Counter and associated methods to get the frequencies and a host of other statistics. Just like this >>> from collections import Counter >>> x=['java', 'python', 'scheme', 'scheme', 'scheme', 'python', 'go', 'go', 'c', ... 'c'] >>> freqs = Counter(x) >>> freqs.most_common(1) [('scheme', 3)] >>>
Why isn't the data written to the database? (DBM, Python 3.2) Question: I have been working to learn the `pickle` and `dbm` python modules. I wrote some code that connected to a dbm database and wrote data and pickled info. import dbm import pickle class PickleDB: def set_dbname(self): self.db = dbm.open("pickle", "n") def get_data(self): self.raw_data = input("Enter your raw data") self.pickled_data = pickle.dumps(self.raw_data) def write_to_db(self): self.db["Raw"] = self.raw_data self.db["Pickled"] = self.pickled_data pickled_db = PickleDB() pickled_db.set_dbname() pickled_db.get_data() pickled_db.write_to_db() Everything works fine while running the program, but problems arise when I try to access the database. The keys aren't available. >>> db = dbm.open("pickle", "n") >>> db["Raw"] Traceback (most recent call last): File "<stdin>", line 1, in <module> KeyError: 'Raw' >>> db.keys() [] Why is this? Why is the data not written to the database? Answer: The issue is that you wipe out your db when you open it up with the option 'n'. From `pydoc dbm`: > 'n' always creates a new database. You might want to take a look at the [shelve package](http://docs.python.org/py3k/library/shelve.html). If I understand what you are trying to do right, "shelve" already does it for you.
How to save nltk Text.similar() with variable Question: I'm a noob in nltk and python.Recently I got a problem,I want to save what text.similar() show in terminal in a variable,but I failed many times.How could I save it? text = nltk.Text(word.lower() for word in nltk.corpus.brown.words()) save = [] for word in nltk.word_tokenize("i want to slove this problem"): save.append(text.similar(word)) Sadly,I found there is nothing in save[].Then I test code "word = text.similar('women')",I also found there is nothing in "word". I realized it seams I couldn't save text.similar(). What should I do to save it? Answer: Instances of `nltk.Text` are really meant only for interactive exploration. It dumps a lot of stuff to the console, but really doesn't return any constructed objects from it's functions. What you want in this case is the `nltk.ContextIndex` class. Using this class... import nltk import nltk.text import nltk.corpus idx = nltk.text.ContextIndex([word.lower( ) for word in nltk.corpus.brown.words( )]) save = [ ] for word in nltk.word_tokenize("i want to solve this problem"): save.append(idx.similar_words(word)) When done, `save` will be a nest list of the most frequent words in the contexts of "i", "want", "to", etc. Take a look at the [online nltk.text.Text documentation](http://nltk.github.com/api/nltk.html#nltk.text.Text), specifically the `similar` method, where it references `nltk.text.ContextIndex`
Python: cannot find the handle with win32gui.FindWindowEx() Question: I'm trying to ge the handle for "Yes" button in a dialog, so I can send the message to click it. I get the dialog and then I try to find the button, but I always get 0 back. import win32gui hwnd = win32gui.FindWindow("#32770", "Programs and Features") # got back the correct handle to the dialog win32gui.SetForegroundWindow(hwnd) btnhdl = win32gui.FindWindowEx(hwnd, 0, "Button", "&Yes") # returns 0 The button is there and the class and title seem to be ok. I verified it by this: def printClasses(childHwnd, lparam): if win32gui.GetWindowText(childHwnd) == "&Yes": print win32gui.GetClassName(childHwnd), win32gui.GetWindowText(childHwnd) return 1 win32gui.EnumChildWindows(hwnd, printClasses, None) # output: Button &Yes Looks like everything should be fine, but why it doesn't return the handle with `FindWindowEx`? Thanks Answer: [From the comments in the OP] Maybe the button is a child of a child, ie a grandchild? IIRC `EnumChildWindow` enumerates recursively while `FindWindowEx` does not.
Convert date format python Question: I have django form and I am receiving from POST a date formated like "%d/%m/%Y" and I would like to convert it to "%Y-%m-%d", How could I do it? Answer: Use [strptime and strftime](http://docs.python.org/library/datetime.html#strftime-strptime- behavior): In [1]: import datetime In [2]: datetime.datetime.strptime('10/05/2012', '%d/%m/%Y').strftime('%Y-%m-%d') Out[2]: '2012-05-10' Likewise, in Django template syntax you can use the [date filter](https://docs.djangoproject.com/en/dev/ref/templates/builtins/?from=olddocs#date): {{ mydate|date:"Y-m-d" }} to print your date in your preferred format.
Can I set the umask for tempfile.NamedTemporaryFile in python? Question: In Python (tried this in 2.7 and below) it looks like a file created using `tempfile.NamedTemporaryFile` doesn't seem to obey the umask directive: import os, tempfile os.umask(022) f1 = open ("goodfile", "w") f2 = tempfile.NamedTemporaryFile(dir='.') f2.name Out[33]: '/Users/foo/tmp4zK9Fe' ls -l -rw------- 1 foo foo 0 May 10 13:29 /Users/foo/tmp4zK9Fe -rw-r--r-- 1 foo foo 0 May 10 13:28 /Users/foo/goodfile Any idea why `NamedTemporaryFile` won't pick up the umask? Is there any way to do this during file creation? I can always workaround this with os.chmod(), but I was hoping for something that did the right thing during file creation. Answer: This is a security feature. The `NamedTemporaryFile` is always created with mode `0600`, hardcoded at [`tempfile.py`, line 235](http://hg.python.org/cpython/file/63bde882e311/Lib/tempfile.py#l235), because it is private to your process until you open it up with `chmod`. There is no constructor argument to change this behavior.
Python programming memory leak? Maybe? File search & destroy script Question: I've got a python script that searches for files in a directory and does so infinitely while the computer is running. Here is the code: import fnmatch import os import shutil import datetime import time import gc # This is a python script that removes the "conflicted" copies of # files that dropbox creates when one computer has the same copy of # a file as another computer. # Written by Alexander Alvonellos # 05/10/2012 class cleanUpConflicts: rootPath = 'D:\Dropbox' destDir = 'D:\Conflicted' def __init__(self): self.removeConflicted() return def cerr(message): f = open('./LOG.txt', 'a') date = str(datetime.datetime.now()) s = '' s += date[0:19] #strip floating point s += ' : ' s += str(message) s += '\n' f.write(s) f.close() del f del s del date return def removeConflicted(self): matches = [] for root, dirnames, filenames in os.walk(self.rootPath): for filename in fnmatch.filter(filenames, '*conflicted*.*'): matches.append(os.path.join(root, filename)) cerr(os.path.join(root, filename)) shutil.move(os.path.join(root, filename), os.path.join(destDir, filename)) del matches return def main(): while True: conf = cleanUpConflicts() gc.collect() del conf reload(os) reload(fnmatch) reload(shutil) time.sleep(10) return main() Anyway. There's a memory leak that adds nearly 1 meg every every ten seconds or so. I don't understand why the memory isn't being deallocated. By the end of it, this script will continuously eat gigs of memory without even trying. This is frustrating. Anyone have any tips? I've tried everything, I think. Here's the updated version after making some of the changes that were suggested here: import fnmatch import os import shutil import datetime import time import gc import re # This is a python script that removes the "conflicted" copies of # files that dropbox creates when one computer has the same copy of # a file as another computer. # Written by Alexander Alvonellos # 05/10/2012 rootPath = 'D:\Dropbox' destDir = 'D:\Conflicted' def cerr(message): f = open('./LOG.txt', 'a') date = str(datetime.datetime.now()) s = '' s += date[0:19] #strip floating point s += ' : ' s += str(message) s += '\n' f.write(s) f.close() return def removeConflicted(): for root, dirnames, filenames in os.walk(rootPath): for filename in fnmatch.filter(filenames, '*conflicted*.*'): cerr(os.path.join(root, filename)) shutil.move(os.path.join(root, filename), os.path.join(destDir, filename)) return def main(): #while True: for i in xrange(0,2): #time.sleep(1) removeConflicted() re.purge() gc.collect() return main() I've done some research effort on this problem and it seems like there might be a bug in fnmatch, which has a regular expression engine that doesn't purge after being used. That's why I call re.purge(). I've tinkered with this for a couple of hours now. I've also found that doing: print gc.collect() Returns 0 with every iteration. Whoever downvoted me is clearly mistaken. I really need some help here. Here's the link that I was talking about: [Why am I leaking memory with this python loop?](http://stackoverflow.com/questions/2184063/why-am-i-leaking-memory- with-this-python-loop) Answer: At a guess, something keeps references to the instances created with each main iteration. Suggestions: 1. Drop the class and make 1-2 functions 2. Drop matches; isn't used? 3. Look at inotify (Linux) or similar for Windows; it can watch the dir and act only when needed; no continuous scanning
incomplete gamma function in python? Question: the `scipy.special.gammainc` can not take negative values for the first argument. Are there any other implementations that could in python? I can do a manual integration for sure but I'd like to know if there are good alternatives that already exist. Correct result: 1 - Gamma[-1,1] = 0.85 Use Scipy: scipy.special.gammainc(-1, 1) = 0 Thanks. Answer: I typically reach for [mpmath](http://code.google.com/p/mpmath/) whenever I need special functions and I'm not too concerned about performance. (Although its performance in many cases is pretty good anyway.) For example: >>> import mpmath >>> mpmath.gammainc(-1,1) mpf('0.14849550677592205') >>> 1-mpmath.gammainc(-1,1) mpf('0.85150449322407795') >>> mpmath.mp.dps = 50 # arbitrary precision! >>> 1-mpmath.gammainc(-1,1) mpf('0.85150449322407795208164000529866078158523616237514084')
String splitting in Python using regex Question: I'm trying to split a string in Python so that I get everything before a certain regex. example string: `"Some.File.Num10.example.txt"` I need everything before this part: `"Num10"`, regex: `r'Num\d\d'` (the number will vary and possibly what comes after). Any ideas on how to do this? Answer: >>> import re >>> s = "Some.File.Num10.example.txt" >>> p = re.compile("Num\d{2}") >>> match = p.search(s) >>> s[:match.start()] 'Some.File.' This would be more efficient that doing a split because search doesn't have to scan the whole string. It breaks on the first match. In your example it wouldn't make a different as the strings are short but in case your string is very long and you know that the match is going to be in the beginning, then this approach would be faster. I just wrote a small program to profile search() and split() and confirmed the above assertion.
check if a URL to an image is up and exists in Python Question: I am making a website. I want to check from the server whether the link that the user submitted is actually an image that exists. Answer: This is one way that is quick: It doesn't really verify that is really an image file, it just guesses based on file extention and then checks that the url exists. If you really need to verify that the data returned from the url is actually an image (for security reasons) then this solution would not work. import mimetypes, urllib2 def is_url_image(url): mimetype,encoding = mimetypes.guess_type(url) return (mimetype and mimetype.startswith('image')) def check_url(url): """Returns True if the url returns a response code between 200-300, otherwise return False. """ try: headers={ "Range": "bytes=0-10", "User-Agent": "MyTestAgent", "Accept":"*/*" } req = urllib2.Request(url, headers=headers) response = urllib2.urlopen(req) return response.code in range(200, 209) except Exception, ex: return False def is_image_and_ready(url): return is_url_image(url) and check_url(url)
python and ctypes cdll, not getting expected return from function Question: I'm in the process of working on interfacing a haptic robot and eye tracker. So, both come with their own programming requirements, namely that the eye tracker software is based in python and is the main language in which I'm programming. Our haptic robot has an API in C, so I've had to write a wrapper in C, compile it as a DLL, and use ctypes in python to load the functions. I've tested my DLL with MATLAB, and everything works just fine. However, something about my implementation of ctypes in my python class is not giving me the expected return value when i query the robot's positional coordinates. I'll post the code here, and a clearer explanation of the problem at the bottom. C source code for DLL wrapper: #include <QHHeadersGLUT.h> using namespace std; class myHapClass{ public: void InitOmni() { DeviceSpace* Omni = new DeviceSpace; //Find a the default phantom } double GetCoord(int index) { HDdouble hapPos[3]; hdGetDoublev(HD_CURRENT_POSITION,hapPos); return hapPos[index]; } }; extern "C" { int index = 1; __declspec(dllexport) myHapClass* myHap_new(){ return new myHapClass();} __declspec(dllexport) void myHapInit(myHapClass* myHapObj){ myHapObj->InitOmni();} __declspec(dllexport) double myHapCoord(myHapClass* myHapObj){ double nowCoord = myHapObj->GetCoord(index); return nowCoord;} } The theory for this code is simply to have 3 available C (not C++) calls that will be compatible with python/ctypes: 1. myHap_new() returns a pointer to an instance of the class 2. myHapInit initializes the haptics device 3. myHapCoord returns a double for the current position, of the axis referenced by int Index. The python class follows here: import sreb from ctypes import cdll lib = cdll.LoadLibrary('C:\Documents and Settings\EyeLink\My Documents\Visual Studio 2010\Projects\myHapDLLSolution\Debug\myHapDLL.dll') class CustomClassTemplate(sreb.EBObject): def __init__(self): sreb.EBObject.__init__(self) self.pyMyHapObj = pyMyHap() self.coordval=2.0 def setCoordval(self,c): self.coordval = c pass def getCoordval(self): return self.coordval def initOmni(self): self.pyMyHapObj.pyHapInit() pass def getCoord(self): self.coordval = self.pyMyHapObj.pyHapCoord() return self.coordval class pyMyHap(object): def __init__(self): self.obj = lib.myHap_new() self.coord = 1.0 def pyHapInit(self): lib.myHapInit(self.obj) def pyHapCoord(self): self.coord = lib.myHapCoord(self.obj) return self.coord The theory of the python custom class is to instantiate an object (self.pyMyHapObj = pyMyHap()) of the loaded DLL class. Making a call to the function 'initOmni' successfully initializes the robot, however a call to 'getCoord' does not return the expected value. In fact, the result I get from 'getCoord' is 1 (and it is listed as 1, not 1.0, so I think it is returning an integer, not a double as it should). In MATLAB, I have use the DLL library, and both the myHapInit and myHapCoord functions work, and I can initialize the robot and query the position coordinates successfully. So what is it about my python class that is causing ctypes to not have the proper value returned from myHapCoord from my DLL? Any help would be appreciated. Thanks edit: Python version 2.3, if it matters... I'm stuck to that version. Answer: Return values default to `int`. Use something like: lib.myHapCoord.restype = ctypes.c_double before calling the function to interpret the return value properly.
Read file and copy to standard output. Question: I'm trying to write a python program that will read input and copy it to standard output (with no alterations). I've been told that it needs to operate as a Python version of the Unix cat function. If a file cannot be opened, an error message needs to be printed, and then the program needs to continue processing any additional files. I am a complete beginner, and have tried my best to scrape something together with my limited knowledge. Here is what I have so far: from sys import argv, stdout, stdin, stderr if len(argv) == 1: try: stdout.write(raw_input(' ') + '\n') except: stderr.write ('sorry' + '\n') quit() else: for filename in argv[1:]: try: filehandle + open(filename) except IOError: stderr.write('Sorry, could not open', filename + '\n') continue f = filehandle.read() stdout.write(f) I am not quite sure where to go from here.. does anyone have any advice/am I on the right track even a little bit? Please and thank you! Answer: This function will copy the specified file to the console line by line (in case you later on decide to give it the ability to use the `-n` command line option of cat) def catfile(fn): with open(fn) as f: for line in f: print line, It can be called with the filename once you have established the file exists.
Override __new__ doubts Question: I will try to simplify the case here, when overriding `__new__` as bellow i don't know the correct way of calling super `__new__` to do the job, am i doing it ok or is there other way of doing this? `super().__new__(cls)` is not producing correct results as i expected i'm a python beginner, please be patient, i'm C++ fluent import weakref class A(str): def __init__(self,s):self.a=s class B(str): def __init__(self,s):self.b=s class P(A,B): manifest=weakref.WeakValueDictionary() def __new__(cls,a,b): o=P.manifest.get(a+b) if not o: print(a,b,super(P,cls)) #i thought this first should be used because __init__ puts the values in #and we index the manifest with parameters [a+b] #o=super().__new__(cls)#produces unique results for all requests?!? #so i called like this and it works (either with a or b) o=super().__new__(cls,a)#why favoring a over b? #o=super().__new__(cls,b)#why favoring b over a? #o=super().__new__(cls,a,b)#its an error (of coz) P.manifest[a+b]=o print("using",id(o)) return o def __init__(self,a,b): A.__init__(self,a) B.__init__(self,b) p=P("a","b") q=P("a","b") r=P("a","x") print(id(p),id(q),id(r)) Answer: I suspect (but I'm not sure) that you are trying to call `__new__` on both your super classes, ie `A` and `B`. The best way to do that depends on a lot of things. The purpose of `P.__new__` is to return an instance of `P`. So that's what you should create. This is indeed what `super().__new__(cls,a)` will do, so that should work fine, however, you could also just call `str.__new__(cls, a)` directly. Usually you actually call `object.__new__`, but since you subclass from `str` you can't do that, it will tell you that it's unsafe in this case. If you do want to use `super()` (and there are cases when this is a good idea) you should typically use it consistently in all of the classes, so it should be used in `A` and `B` as well, and not only in `__new__` but also in `__init__` class A(str): def __init__(self, s): super().__init__(s) self.a = s def __new__(cls, s): return super().__new__(cls, s) class B(str): def __init__(self, s): super().__init__(s) self.b = s def __new__(cls, s): return super().__new__(cls, s) However, that becomes problematic here as you don't have the same function profile, since P takes two parameters. This can be take as an indication that your solution may not be the best one. Especially since P is a string that takes two strings as parameters, that doesn't make much sense. In your previous question, you talked about polymorphism, and this is a pattern that break that polymorphism somewhat, as P doesn't have the same API as A and B, and hence can't be used interchangeably. The result is that I suspect that subclassing is the wrong solution here. Also, I'm guessing you are trying to cache the objects so that creating new objects with the same parameters will actually return the same object. I suggest you instead use a factory method for that, instead of overriding `__new__`.
Delete Files from Google Cloud Storage Question: So I've got a django application up and running on appengine and have it creating files when a user uploads them. The issue I'm having is trying to figure out how to delete them. My code for creating them looks like. from google.appengine.api import files file = request.FILES['assets_thumbnail'] filename = '/gs/mybucketname/example.jpg' writable_file_name = files.gs.create(filename, mime_type='image/jpeg', acl='public-read') with files.open(writable_file_name, 'a') as f: f.write(file.read()) files.finalize(writable_file_name) This works fine, but in the documentation at: <https://developers.google.com/appengine/docs/python/googlestorage/functions> there isn't a delete method listed. However, if you look at the actual source for google.appengine.api.files at the link below (line 504) <http://code.google.com/p/googleappengine/source/browse/trunk/python/google/appengine/api/files/file.py> There is a delete method that I can call, but I can't figure out for the life of me exactly the argument it wants. I've tried plenty of different combinations with the bucket name and such. It seems to want it to start with /blobstore/ which is different than anything else I've done so far when interacting with Cloud Storage. I've been looking through the underlying blobstore classes that google.appengine.api.files is written on top of, but still can't figure out exactly how to delete items. It looks like I may need to find the BlobKeys for the items I've uploaded. I can delete them fine using the web based bucket manager that google hosts and also the gsutil command line utility that they provide. Has anyone successfully deleted files from google cloud storage via a python app deployed to app engine? Any clues/thoughts/ideas are greatly appreciated. Answer: AppEngine release 1.7.0 has support for deleting Google Storage objects using bigstore API. key = blobstore.create_gs_key('/gs/my_bucket/my_object') blobstore.delete(key) Alternatively, you can use the rest API to make a call out to Google Storage to delete the file. <https://developers.google.com/storage/docs/reference-methods#deleteobject>
How do I run a Python script in the command line with an embedded text file? Question: there. I apologize for the simple question, but I am a complete novice and need some help. I am trying to run Peter Norvig's Spelling Corrector (http://norvig.com/spell.py), but I'm receiving the following reply: C:\>spelling.py Traceback (most recent call last): File "C:\Python27\spelling.py", line 11, in <module> NWORDS = train(words(file('big.txt').read())) IOError: [Errno 2] No such file or directory: 'big.txt' The script includes an embedded text file (big.txt), which I've created and saved in the same directory as spelling.py. Why can't it find the big.txt file? Secondly, once the script is working, how would I use it against a sample of words needing correction? Answer: The working directory of your script is the current folder, not the script's folder. You can add the following code to your script to change this: import os os.chdir(os.path.dirname(os.path.abspath(__file__))) Of course you could also use this folder only when opening the file instead of changing the working directory: path = os.path.join(os.path.dirname(os.path.abspath(__file__)), 'big.txt') NWORDS = train(words(file(path).read()))
Multiple Domain Hosting With One Django Project Question: I'm new to Django and python in general, so please bear with me. I want to create a very simple SaaS app to get started with Django and python. My design dictates that all domains will run on the same codebase. The only thing that will differ between each website is the database connection details. (IE each domain receives its own database. All databases contain the same schema) How would I go about this with Django? I've seen the Sites framework, but I'm not sure that's what I'm looking for. Essentially, I'd like to either A) Have Django look up the database connection details from a MASTER database, when the page loads, and then use those details when connecting to the site database B) Have a settings.py per-site and have django include the correct file at runtime (IE settings_domain.py) C) Have the index WSGI include the appropriate settings file based on the accessing domain (This seems like it could work, but I'm sure I'm missing a potential pitfall of this implementation) D) Some other implementation I haven't thought of.... Am I making this more complicated than it needs to be? How can I easily implement this functionality into a new django project? Answer: Well, there's an interesting project at: <https://bitbucket.org/uysrc/django- dynamicsites>. It attempts to let you have entirely unique sites all running off the same project. However, currently, I don't think it will do much for you since you're going to need a bit more customization over settings than it offers. I actually just did this myself, and originally tried to use django- dynamicsites, but found it a little too touchy and not quite right for my project. As a result, I ended up taking a little bit different approach. My project has a "sites" module and in that a module for each unique site. Each module has it's own settings.py and urls.py and templates directory. For example: sites - __init__.py - site1 - __init__.py - settings.py - urls.py - templates - base.html - site 2 - __init__.py - settings.py - urls.py - templates - base.html Each settings.py looks roughly like this: from myproject.settings import * SITE_ID = 1 URL_CONF = 'sites.site1.urls' SITE_ROOT = os.path.dirname(__file__) TEMPLATE_DIRS = ( os.path.join(SITE_ROOT, 'templates') ) CACHE_MIDDLEWARE_KEY_PREFIX = 'site1' So, what this does is import your projects settings file, and then overrides the settings that are unique to the site. Then, all you have to do is make sure whatever server you're using loads the particular site's settings.py instead of the main project settings.py. I'm using a combo of nginx+Gunicorn, so here's roughly how that config looks: **site1.conf (nginx)** upstream site1 { server 127.0.0.1:8001 fail_timeout=0; } server { listen 80; server_name site1.domain.com; root /path/to/project/root; location / { try_files $uri @proxy; } location @proxy { proxy_pass_header Server; proxy_set_header Host $http_host; proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for; proxy_set_header X-Real-IP $remote_addr; proxy_set_header X-Scheme $scheme; proxy_connect_timeout 10; proxy_read_timeout 30; proxy_pass http://site1; proxy_redirect off; } } I use supervisor to manage the Gunicorn server, so here's my config for that: **site1.conf (supervisor)** [program:site1] command=/path/to/virtualenv/bin/python manage.py run_gunicorn --settings=sites.site1.settings directory=/path/to/project/root user=www-data autostart=true autorestart=true redirect_stderr=True The important part is that there's no fancy Django middleware or such checking for particular hosts and going this way or that accordingly. You fire up a Django instance for each on uwsgi, Gunicorn, etc. pointing to the right settings.py file, and your webserver proxies the requests for each subdomain to the matching upstream connection.
mod_wsgi error - class.__dict__ not accessible in restricted mode Question: This started biting our ass on our production server really hard. We saw this occasionally (for 1 request per week). Back then we found out it is because of mod_wsgi doing some funky stuff in some configs. As we could not track the reason for the bug, we decided that it did not require instant attention. However today, on 1 of our production servers this really occurred for 10 % of all server requests; that is 10 % of all server requests failed with this very same error: mod_wsgi (pid=1718): Target WSGI script '/installation/dir/our-program/prod-dispatch.wsgi' cannot be loaded as Python module. mod_wsgi (pid=1718): Exception occurred processing WSGI script '/installation/dir/our-program/prod-dispatch.wsgi'. Traceback (most recent call last): File "/installation/dir/our-program/prod-dispatch.wsgi", line 7, in <module> from pyramid.paster import get_app File "/installation/dir/venv/local/lib/python2.7/site-packages/pyramid-1.3a6-py2.7.egg/pyramid/paster.py", line 12, in <module> from pyramid.scripting import prepare File "/installation/dir/venv/local/lib/python2.7/site-packages/pyramid-1.3a6-py2.7.egg/pyramid/scripting.py", line 1, in <module> from pyramid.config import global_registries File "/installation/dir/venv/local/lib/python2.7/site-packages/pyramid-1.3a6-py2.7.egg/pyramid/config/__init__.py", line 61, in <module> from pyramid.config.assets import AssetsConfiguratorMixin File "/installation/dir/venv/local/lib/python2.7/site-packages/pyramid-1.3a6-py2.7.egg/pyramid/config/assets.py", line 83, in <module> @implementer(IPackageOverrides) File "/installation/dir/venv/local/lib/python2.7/site-packages/zope.interface-3.8.0-py2.7-linux-x86_64.egg/zope/interface/declarations.py", line 480, in __ classImplements(ob, *self.interfaces) File "/installation/dir/venv/local/lib/python2.7/site-packages/zope.interface-3.8.0-py2.7-linux-x86_64.egg/zope/interface/declarations.py", line 445, in cl spec = implementedBy(cls) File "/installation/dir/venv/local/lib/python2.7/site-packages/zope.interface-3.8.0-py2.7-linux-x86_64.egg/zope/interface/declarations.py", line 285, in im spec = cls.__dict__.get('__implemented__') RuntimeError: class.__dict__ not accessible in restricted mode Ubuntu Precise, 64bit, with latest Apache, mod_wsgi, Python 2.7, using mpm_worker + mod_wsgi in _daemon_ mode. This is the only program running on the server and there is only one wsgi interpreter in the config. Is this because of mpm_worker spawning new threads or what? More importantly - how do we fix it. We have the following to subdivide requests to 4 daemon processes based on a cookie. WSGIPythonOptimize 1 WSGIDaemonProcess sticky01 processes=1 threads=16 display-name=%{GROUP} WSGIDaemonProcess sticky02 processes=1 threads=16 display-name=%{GROUP} WSGIDaemonProcess sticky03 processes=1 threads=16 display-name=%{GROUP} WSGIDaemonProcess sticky04 processes=1 threads=16 display-name=%{GROUP} <VirtualHost *:81> ... WSGIRestrictProcess sticky01 sticky02 sticky03 sticky04 WSGIProcessGroup %{ENV:PROCESS} ... WSGIScriptAlias / /installation/dir/our-program/prod-dispatch.wsgi </VirtualHost> Answer: It has been known for ages that multiple subinterpreters don't play well along C extensions. However, what I did not realize is that the default settings are very unfortunate. [ModWSGI wiki](http://code.google.com/p/modwsgi/wiki/ConfigurationDirectives#WSGIApplicationGroup) clearly states that the default value for WSGIApplicationGroup directive is %{RESOURCE} the effect of which shall be that > The application group name will be set to the server hostname and port as > for the %{SERVER} variable, to which the value of WSGI environment variable > SCRIPT_NAME is appended separated by the file separator character. This means that for each Host: header ever encountered while accessing the server the mod_wsgi kindly spawns a new subinterpreter, for which the C extensions are then loaded. I had unknowingly triggered the error by accessing localhost.invalid:81 with _links_ browser on this local server causing 1 of our 4 WSGIDaemonProcesses to fail for all future incoming requests. Summa summarum: **always when using mod_wsgi with pyramid or any other framework that uses C extensions, make sure that WSGIApplicationGroup is always set to %{GLOBAL}**. In other words, the result of using the default settings will cause you to shoot yourself in the foot, after which you might want to shoot yourself in the head too.
pytest automation apparently running tests during test collection phase Question: Running webui automated tests with pytest and selenium; having an issue where it appears that my tests are actually running during the _collection_ phase. During this phase, I would expect pytest to be collecting tests - not running them. The end result is I end up with 6 test results where I would expect 2. Now the interesting piece, the 6 results only appear in the HTML report; on the command line I only get the expected 2 lines of output (but it 300 seconds to run those two tests because the tests are literally running multiple times). tests/test_datadriven.py #!/usr/bin/env python from unittestzero import Assert from pages.home import Home from pages.administration import RolesTab from api.api import ApiTasks import time import pytest from data.datadrv import * class TestRolesDataDriven(object): scenarios = [scenario1,scenario2] @pytest.mark.challenge def test_datadriven_rbac(self, mozwebqa, org, perm_name, resource, verbs, allowed, disallowed): """ Perform a data driven test related to role based access controls. All parameters are fullfilled by the data. :param org: Organization Name :param perm_name: Permission name :param resource: Resource :param verbs: A tuple of verbs :returns: Pass or Fail for the test """ sysapi = ApiTasks(mozwebqa) home_page = Home(mozwebqa) rolestab = RolesTab(mozwebqa) role_name = "role_%s" % (home_page.random_string()) perm_name = "perm_%s" % (home_page.random_string()) username = "user%s" % home_page.random_string() email = username + "@example.com" password = "redhat%s" % (home_page.random_string()) sysapi.create_org(org) sysapi.create_user(username, password, email) home_page.login() home_page.tabs.click_tab("administration_tab") home_page.tabs.click_tab("roles_administration") home_page.click_new() rolestab.create_new_role(role_name) rolestab.click_role_permissions() rolestab.role_org(org).click() rolestab.click_add_permission() rolestab.select_resource_type(resource) home_page.click_next() for v in verbs: home_page.select('verbs', v) home_page.click_next() rolestab.enter_permission_name(perm_name) rolestab.enter_permission_desc('Added by QE test.') rolestab.click_permission_done() rolestab.click_root_roles() rolestab.click_role_users() rolestab.role_user(username).add_user() home_page.header.click_logout() home_page.login(username, password) for t in allowed: Assert.true(t(home_page)) for t in disallowed: Assert.false(t(home_page)) data/data.py ### # DO NOT EDIT HERE ### def pytest_generate_tests(metafunc): """ Parse the data provided in scenarios. """ idlist = [] argvalues = [] for scenario in metafunc.cls.scenarios: idlist.append(scenario[0]) items = scenario[1].items() argnames = [x[0] for x in items] argvalues.append(([x[1] for x in items])) metafunc.parametrize(argnames, argvalues, ids=idlist) ### # EDIT BELOW # ADD NEW SCENARIOS ### scenario1 = ('ACME_Manage_Keys', { 'org': 'ACME_Corporation', 'perm_name': 'ManageAcmeCorp', 'resource': 'activation_keys', 'verbs': ('manage_all',), 'allowed': (Base.is_system_tab_visible, Base.is_new_key_visible, Base.is_activation_key_name_editable), 'disallowed': (Base.is_dashboard_subs_visible,)}) scenario2 = ('Global_Read_Only', { 'org': 'Global Permissions', 'perm_name': 'ReadOnlyGlobal', 'resource': 'organizations', 'verbs': ('read','create'), 'allowed': (Base.is_organizations_tab_visible, Base.is_new_organization_visible, Base.is_new_organization_name_field_editable), 'disallowed': (Base.is_system_tab_visible, Base.is_new_key_visible)}) Full source is available at github; <https://github.com/eanxgeek/katello_challenge> Anyone have any idea what might be going on here? I am using the pytest- mozwebqa plugin, pytests, and selenium. Thanks! Answer: Check the version of pytest-mozwebqa you have installed. If your installed version is < 0.10 then you must update. pip-python install --upgrade pytest-mozwebqa Due to the number of changes in pytest-mozwebqa I strongly encourage you to test first in a python virtualenv.
how to stream jpeg frame from java client to python server Question: i am developing an android application wherein i have to send a frame in jpeg format allocated to a BufferedArrayOutputStream (baos variable in code). I convert this baos into a byte array to write into the socket. On the server side i would like to reconstruct the image in jpeg format. If i write the data received in a variable to a '.jpg' file on the server, on opening the file, it gives an error like "file starting with ffx0 not jpeg format". I think this is because the string variable in python writes the data in the file as a hex string. The client code is as follows :- Bitmap memoryImage = Bitmap.createBitmap(rgb, previewSize.width,previewSize.height,Bitmap.Config.ARGB_8888); ByteArrayOutputStream baos = new ByteArrayOutputStream(); if(memoryImage.compress(CompressFormat.JPEG,100, baos)){ try { if(count==0){ byte [] Finalbaos = baos.toByteArray(); int tempLen = Finalbaos.length; Log.v("Client","ImageBytes :"+ tempLen); String dataMeta = Integer.toString(tempLen); Log.v("Client","Integer Size :"+ dataMeta.length()); PrintWriter tempOut = new PrintWriter(socket.getOutputStream()); if(tempOut!=null){ tempOut.write(dataMeta); Log.v("Client","data size sent"); tempOut.flush(); } DataInputStream in = new DataInputStream(socket.getInputStream()); if(in!=null){ Log.v("Client","read buffer created"); String xyz = in.readLine(); String temp = "recvd"; Log.v("Client",xyz); if(xyz.equals(temp)){ OutputStream out = socket.getOutputStream(); out.write(Finalbaos,0,tempLen); out.flush(); Log.d("Client", "Client sent message"); } } server code: import socket,thread import string import array host="" port=54321 s=socket.socket() s.setsockopt(socket.SOL_SOCKET,socket.SO_REUSEADDR,1) s.bind((host,port)) s.listen(5) conn,address=s.accept() data="" mylen=0 dataRecv=0 file1 = open("myfile.jpg","w") totalLength="" length=conn.recv(1024) conn.send("recvd") mylen=int(length) while dataRecv<mylen: newData="" newData=conn.recv(1) if not newData: break data+=newData dataRecv+=len(newData) result= array.array('B',data.decode("hex")) file1.write(result) file1.close() print len(data) conn.close() s.close() can anyone let me know how to reconstruct the frame on server either in python or C++ Answer: * `mylen=len(length)` doesn't give you the length you're trying to send. it gives you how many bytes were read in the previsous `recv`. So you get the wrong lenght there. * on your client side, you use `String xyz = in.readLine();` which will block until a newline character is encountered. but you never send a `'\n'` on the server side, instead you go waiting for a response from the client. so you have a deadlock there. * you use `data.decode("hex")` on your recieved data. unless you do the equivalend of `data.encode("hex")` in java on the other side, that won't work. it should give you an error if the string is not a valid hex-representation of a binary string. * `result` is an `array.array`, which you write to file. `file1.write` expects a string as argument, it gives you an error if you pass your `result` object. so i can't even see why your code works at all, and why there's anything at all in your file.
How to do a basic query on yahoo search engine using Python without using any yahoo api? Question: I want to do a basic query on yahoo search engine from a python script using Beautiful Soup and urllib. I've done the same for Google which was rather easy but Yahoo is proving to be a bit difficult. A minimal example script of a query to yahoo search engine would help. Thank you! Answer: first, avoid `urllib` \- use [requests](https://github.com/kennethreitz/requests) instead, it's a much saner interface. Then, all links in the returned page have the class `yschttl` and an ID following the scheme `link-1`, `link-2` and so on. That you can use with beautiful soup: import requests from bs4 import BeautifulSoup url = "http://search.yahoo.com/search?p=%s" query = "python" r = requests.get(url % query) soup = BeautifulSoup(r.text) soup.find_all(attrs={"class": "yschttl"}) for link in soup.find_all(attrs={"class": "yschttl"}): print "%s (%s)" %(link.text, link.get('href')) Gives us > > Python Programming Language – Official Website (http://www.python.org/) > Python - Image Results > (http://images.search.yahoo.com/search/images?_adv_prop=image&va=python) > Python (programming language) - Wikipedia, the free encyclopedia > (http://en.wikipedia.org/wiki/Python_(programming_language)) > and more.
How to send a function to a remote Pyro object Question: I am trying to set up some code using Pyro to process python code functions on a remote host and get results back. After starting the name server, i would execute this code on the remote host (actually still on localhost): import Pyro4 class Server(object): def evaluate(self, func, args): return func(*args) def main(): server = Server() Pyro4.Daemon.serveSimple( { server: "server" }, ns=True) if __name__ == '__main__': main() On the client side i have this code, which is an example of the behaviour i am trying to set up. import Pyro4 remoteServer = Pyro4.Proxy('PYRONAME:server') def square(x): return x**2 print remoteServer.evaluate(square, 4) However, this code results in the following exception: /usr/lib/python2.7/site-packages/Pyro4/core.py:155: UserWarning: HMAC_KEY not set, protocol data may not be secure warnings.warn("HMAC_KEY not set, protocol data may not be secure") Traceback (most recent call last): File "/home/davide/Projects/rempy/example-api-pyro.py", line 7, in <module> print remoteServer.evaluate(square, 4) File "/usr/lib/python2.7/site-packages/Pyro4/core.py", line 149, in __call__ return self.__send(self.__name, args, kwargs) File "/usr/lib/python2.7/site-packages/Pyro4/core.py", line 289, in _pyroInvoke raise data AttributeError: 'module' object has no attribute 'square' It seems to me that the function object is pickled correctly and is sent to the Server instance on the remote host, but there is some problem in the namespace. How can i solve this problem? Thanks Answer: I think i know your problem: the module the function is defiined in is called '__main__' it exists in all running versions of python. pickle does not transfer the source code but a reference __main__.square so you have two possibilities: source square out and make the main module as short as possible such as: # main.py def square(x): return x**2 import Pyro4 def main(): remoteServer = Pyro4.Proxy('PYRONAME:server') print remoteServer.evaluate(square, 4) and: # __main__.py import main main.main() Then the server can import exactly the same module from the file. or create a module with my code: class ThisShallNeverBeCalledError(Exception): pass class _R(object): def __init__(self, f, *args): self.ret = (f, args) def __reduce__(self): return self.ret def __call__(self, *args): raise ThisShallNeverBeCalledError() @classmethod def fromReduce(cls, value): ret = cls(None) ret.ret = value return ret def dump_and_load(obj): '''pickle and unpickle the object once''' s = pickle.dumps(obj) return pickle.loads(s) # this string creates an object of an anonymous type that can # be called to create an R object or that can be reduced by pickle # and creates another anonymous type when unpickled # you may not inherit from this MetaR object because it is not a class PICKLABLE_R_STRING= "type('MetaR', (object,), " \ " {'__call__' : lambda self, f, *args: "\ " type('PICKLABLE_R', "\ " (object,), "\ " {'__reduce__' : lambda self: (f, args), "\ " '__module__' : 'pickleHelp_', "\ " '__name__' : 'PICKLABLE_R', "\ " '__call__' : lambda self: None})(), "\ " '__reduce__' : lambda self: "\ " self(eval, meta_string, "\ " {'meta_string' : meta_string}).__reduce__(), "\ " '__module__' : 'pickleHelp_', "\ " '__name__' : 'R'})()".replace(' ', '') PICKLABLE_R = _R(eval, PICKLABLE_R_STRING, \ {'meta_string' : PICKLABLE_R_STRING}) R = dump_and_load(PICKLABLE_R) del PICKLABLE_R, PICKLABLE_R_STRING PICKLABLE___builtins__ = R(vars, R(__import__, '__builtin__')) PICKLABLE_FunctionType = R(type, R(eval, 'lambda:None')) ##R.__module__ = __name__ ##R.__name__ = 'PICKLABLE_R' def packCode(code, globals = {}, add_builtins = True, use_same_globals = False, \ check_syntax = True, return_value_variable_name = 'obj', __name__ = __name__ + '.packCode()'): '''return an object that executes code in globals when unpickled use_same_globals if use_same_globals is True all codes sent through one pickle connection share the same globals by default the dont return_value_variable_name if a variable with the name in return_value_variable_name exists in globals after the code execution it is returned as result of the pickling operation if not None is returned __name__ ''' if check_syntax: compile(code, '', 'exec') # copying locals is important # locals is transferred through pickle for all code identical # copying it prevents different code from beeing executed in same globals if not use_same_globals: globals = globals.copy() if add_builtins: globals['__builtins__'] = PICKLABLE___builtins__ globals.setdefault('obj', None) # get the compilation code # do not marshal or unmarshal code objects because the platforms may vary code = R(compile, code, __name__, 'exec') # the final object that can reduce, dump and load itself obj = R(R(getattr, tuple, '__getitem__'), ( R(R(PICKLABLE_FunctionType, code, globals)), R(R(getattr, type(globals), 'get'), globals, \ returnValueVariableName, None) ), -1) return obj and then send this to the other side: packCode(''' def square(...): ... ''', return_value_variable_name = 'square') and the function will come out on the other side, no module code is needed to transefer this python function to the other server side. If something does not work out please tell me.
python - Overhead on looping over an iterable class Question: I was fiddling around with Python's generators and iterable class, just for fun. Basically I wanted test out something that I've never been too sure about: that classes in Pythons have some significant overhead and it's better to rely on methods that implement `yield` instead of classes that implement an iterator protocol, if you can. I couldn't find a satisfying explanation on this topic in Google, so I decided to test them out on my own using these two simple scripts: `func_iter.py` and `class_iter.py` Here's `func_iter.py`: #!/usr/bin/env python import time x = 0 def create_generator(num): mylist = range(num) for i in mylist: yield i t = time.time() gen = create_generator(100000) for i in gen: x = x + i print "%.3f" % (time.time() - t) And here's `class_iter.py`: #!/usr/bin/env python import time x = 0 class Generator(object): def __init__(self, num): self.start = 0 self.end = num def __iter__(self): return self def next(self): if self.start == self.end: raise StopIteration else: self.start = self.start + 1 return self.start t = time.time() gen = Generator(100000) for i in gen: x = x + i print "%.3f" % (time.time() - t) I then ran each of them 10 times using this in bash (for `class_iter.py`, for example): for i in {1..10}; do ./class_iter.py; done And here are the average running times for each of them: class_iter.py: 0.0864 func_iter.py: 0.0307 Now, my questions are: 1. Are my methods correct? Is my comparison fair? 2. If so, why the big difference? Why did `class_iter.py` take almost three times as long as `func_iter.py` to run? 3. If not, how can I improve my methods or come up with a better comparison? EDIT: As Dacav suggested, I also tried running `func_iter.py` using `xrange` instead of `range`. This decreases its average running time to 0.0263 seconds. Answer: The class version spends lots of time accessing its own variables. Each `self.whatever` costs cycles. If you define your `__iter__` as a generator and minimize the use of instance variables, the difference between class and function versions will be negligible: setup = """ def create_generator(num): mylist = range(num) for i in mylist: yield i class Generator(object): def __init__(self, num): self.start = 0 self.end = num def __iter__(self): return self def next(self): if self.start == self.end: raise StopIteration else: self.start = self.start + 1 return self.start class Generator2(object): def __init__(self, num): self.mylist = range(num) def __iter__(self): for i in self.mylist: yield i """ import timeit print timeit.timeit('for p in create_generator(1000):p', setup, number=1000) print timeit.timeit('for p in Generator(1000):p', setup, number=1000) print timeit.timeit('for p in Generator2(1000):p', setup, number=1000) Results: 0.158941984177 0.696810007095 0.160784959793 so the second generator class is almost as fast as the function version. Please do note that `Generator` and `Generator2` in the example are not fully equivalent, there are cases when you cannot simply replace a "plain" iterator with a generator (e.g. marshaling).
How to start a loop with a specific iterator Question: I want to loop through a list in several loops always starting with the item of the last loop: import itertools as it list1=[1,2,3,4,5,6,7,8] a=iter(list1) while a.next()!= 8: a,b=it.tee(a) #copy the iterator while b.next()!=8: b,c=it.tee(b) while c.next()!=8: print "yaaay" in this code I can start my loop with the current iterator of the outer loop. How to do this in a more pythonic way not using slice? here is an example of what I'm thinking of a more pythonic way: list1=[1,2,3,4,5,6,7,8] a=iter(list1) for k1 in list1: for k2=k1 in list1: for k3=k2 in list1: print "yaaay" Answer: From my understanding, you're looking for the way to "save" the generator state at some point and then "restore" it. Using `tee` is the correct idea, [PEP 0323](http://www.python.org/dev/peps/pep-0323/) has more info on this. import itertools lst = range(10) it = iter(lst) while True: print it.next(), '>>', it, saved = itertools.tee(it) for subitem in it: print subitem, it = saved print Update: import itertools class fancy_it(object): stack = [] def __init__(self, iterable=None): if not iterable: prev = fancy_it.stack[-1] prev.it, iterable = itertools.tee(prev.it) self.it = iter(iterable) def __iter__(self): fancy_it.stack.append(self) try: while True: yield self.it.next() except StopIteration: fancy_it.stack.pop() raise StopIteration for x in fancy_it(range(10)): print x for y in fancy_it(): print '**', y for z in fancy_it(): print '****', z
wxPython StyleSetSpec and SetLexer not working? Question: Ok, let's get straight to the point. I got 2 questions 1\. Why self.StyleSetSpec(stc.STC_STYLE_DEFAULT, "fore:#000000" + FontSet) not working? 2\. Why the custom lexer is not applied? This is the source code import wx, re, keyword from wx import stc class BaseLexer(object): """Defines simple interface for custom lexer objects""" def __init__(self): super(BaseLexer, self).__init__() def StyleText(self, event): raise NotImplementedError class STC_LEX_VOTONUSA(BaseLexer): # Define some style IDs STC_VOTONUSA_DEFAULT = wx.NewId() STC_VOTONUSA_VALUE = wx.NewId() STC_VOTONUSA_OBJECT = wx.NewId() STC_VOTONUSA_TYPE = wx.NewId() STC_VOTONUSA_OPERATION = wx.NewId() STC_VOTONUSA_COMMENT =wx.NewId() STC_VOTONUSA_QUALIFIER = wx.NewId() def __init__(self): super(STC_LEX_VOTONUSA, self).__init__() # Attributes self.Comment = re.compile(""" // """, re.X) self.Types = re.compile(""" \\b (void|integer|shortint|(short)?word|float|boolean|char|record|program|module) \\b """, re.I|re.X) self.Operation = re.compile(""" (read|write)(line)?|if|main|case|while|use|return|exit|in_case|repeat_until (\+|-|\*|/|%|\*\*|:|!|<|>)?=?| (\{|\}|\(|\)|\[|\]) """, re.I|re.X) self.Value = re.compile(""" [(`\d*)+\'\w*\']*|\'.*\'|[\+-]*\d*\.?\d* """, re.I|re.X) self.Qualifier = re.compile(""" interface|implementation """, re.I|re.X) self.Object = re.compile(""" s """, re.I|re.X) def GetLastWord(self, Line, CaretPos): """ Get the last word from a line """ LastWord = re.search( """ \s* ( ".*"| # String data type \w*| # Any letter/number (\+|-|\*|/|%|\*\*|:|!|<|>)?=?| # Assignment, Comparison & Mathematical (\{|\}|\(|\)|\[|\]) # Brackets ) \s*\Z """, Line[:CaretPos], re.VERBOSE) return LastWord def StyleText(self, event): """Handle the EVT_STC_STYLENEEDED event""" Obj = event.GetEventObject() # Get Last Correctly Styled LastStyledPos = Obj.GetEndStyled() # Get Styling Range Line = Obj.LineFromPosition(LastStyledPos) StartPos = Obj.PositionFromLine(Line) EndPos = event.GetPosition() # Walk the Range and Style Them while StartPos < EndPos: Obj.StartStyling(StartPos, 0x1f) LastWord = self.GetLastWord(Line, CaretPos) if self.Comment.search(LastWord): # Set Comment Keyword style Style = self.STC_VOTONUSA_COMMENT elif self.Type.search(LastWord): # Set Type Keyword style Style = self.STC_VOTONUSA_TYPE elif self.Operation.search(LastWord): # Set Operation Keyword style Style = self.STC_VOTONUSA_OPERATION elif self.Value.search(LastWord): # Set Value Keyword style Style = self.STC_VOTONUSA_VALUE elif self.Qualifier.search(LastWord): # Set Qualifier Keyqord style Style = self.STC_VOTONUSA_QUALIFIER elif self.Object.search(LastWord): # Set Object Keyword style Style = self.STC_VOTONUSA_OBJECT # Set the styling byte information for length of LastWord from # current styling position (StartPos) with the given style. Obj.SetStyling(len(LastWord), Style) StartPos += len(LastWord) class CustomSTC(stc.StyledTextCtrl): def __init__(self, parent): super(CustomSTC, self).__init__(parent) # Attributes self.custlex = None Font = wx.Font(12, wx.FONTFAMILY_MODERN, wx.FONTSTYLE_NORMAL, wx.FONTWEIGHT_NORMAL) Face = Font.GetFaceName() Size = Font.GetPointSize() # Setup kwlist = u" ".join(keyword.kwlist) self.SetKeyWords(0, kwlist) self.StyleClearAll() self.SetLexer(wx.NewId(), STC_LEX_VOTONUSA) self.EnableLineNumbers() FontSet = "face:%s, size:%d" % (Face, Size) self.StyleSetSpec(stc.STC_STYLE_LINENUMBER, FontSet) # Set Default to Black self.StyleSetSpec(stc.STC_STYLE_DEFAULT, "fore:#000000" + FontSet) # Set Comment to Pink self.StyleSetSpec(STC_LEX_VOTONUSA.STC_VOTONUSA_COMMENT, "fore:#ff007f" + FontSet) # Set Value to Green self.StyleSetSpec(STC_LEX_VOTONUSA.STC_VOTONUSA_VALUE, "fore:#00ff00" + FontSet) # Set Object to Brown self.StyleSetSpec(STC_LEX_VOTONUSA.STC_VOTONUSA_OBJECT, "fore:#a52a2a" + FontSet) # Set Type to Red self.StyleSetSpec(STC_LEX_VOTONUSA.STC_VOTONUSA_TYPE, "fore:#ff0000" + FontSet) # Set Operation to Blue self.StyleSetSpec(STC_LEX_VOTONUSA.STC_VOTONUSA_OPERATION, "fore:#0000ff" + FontSet) # Set Qualifier to Orange self.StyleSetSpec(STC_LEX_VOTONUSA.STC_VOTONUSA_QUALIFIER, "fore:#cc3232" + FontSet) # Event Handlers self.Bind(stc.EVT_STC_STYLENEEDED, self.OnStyle) def EnableLineNumbers(self, enable=True): """Enable/Disable line number margin""" if enable: self.SetMarginType(1, stc.STC_MARGIN_NUMBER) self.SetMarginMask(1, 0) self.SetMarginWidth(1, 25) else: self.SetMarginWidth(1, 0) def OnStyle(self, event): # Delegate to custom lexer object if one exists if self.custlex: self.custlex.StyleText(event) else: event.Skip() def SetLexer(self, lexerid, lexer=None): """ Overrides StyledTextCtrl.SetLexer Adds optional param to pass in custom container lexer object. """ self.custlex = lexer super(CustomSTC, self).SetLexer(lexerid) class NUSAIPT(wx.Frame): def __init__(self, *args, **kwargs): wx.Frame.__init__(self, None, wx.ID_ANY, 'VOTO NUSA IPT') self.TextArea = CustomSTC(self) self.Show() app = wx.App() frame = NUSAIPT() app.MainLoop() If I change self.SetLexer(wx.NewId(), STC_LEX_VOTONUSA) into self.SetLexer(stc.STC_LEX_CPP) and self.StyleSetSpec(STC_LEX_VOTONUSA.STC_VOTONUSA_COMMENT, "fore:#ff007f" + FontSet) into self.StyleSetSpec(stc.STC_C_COMMENT, "fore:#ff007f" + FontSet) the comment highlighting worked. so the mistake should be in `self.SetLexer(wx.NewId(), STC_LEX_VOTONUSA)` or `STC_LEX_VOTONUSA.STC_VOTONUSA_COMMENT` Thanks in advance. Hope to see some answer soon. Answer: Just stuck with same problem yesterday, here are my results. Hope it's not too late :) First, i set lexer to this one, and internal lexer as you do: self.SetLexer(stc.STC_LEX_CONTAINER) self.custlex = SCT_LEX_ERLANG_IDNOISE(self) Bind to event and OnStyle method are same. And also i changed id of styles from `wx.newId()` to just numbers starting from 1. Without it i didn't see any styling at all. Also `stc.STC_STYLE_DEFAULT` started to work too. Full listing: class SCT_LEX_ERLANG_IDNOISE(BaseLexer): STC_ERLANG_IDNOISE_DEFAULT = 1 STC_ERLANG_IDNOISE_VARIABLE = 2 STC_ERLANG_IDNOISE_ATOM = 3 STC_ERLANG_IDNOISE_MODULE = 4 STC_ERLANG_IDNOISE_KEYWORD = 5 STC_ERLANG_IDNOISE_COMMENT = 6 STC_ERLANG_IDNOISE_MACROS = 7 STC_ERLANG_IDNOISE_NUMBER = 8 def __init__(self, control): super(SCT_LEX_ERLANG_IDNOISE, self).__init__(control) self.typeFormatDict = {} self.typeFormatDict["other"] = SCT_LEX_ERLANG_IDNOISE.STC_ERLANG_IDNOISE_DEFAULT self.typeFormatDict["variable"] = SCT_LEX_ERLANG_IDNOISE.STC_ERLANG_IDNOISE_VARIABLE self.typeFormatDict["atom"] = SCT_LEX_ERLANG_IDNOISE.STC_ERLANG_IDNOISE_ATOM self.typeFormatDict["module"] = SCT_LEX_ERLANG_IDNOISE.STC_ERLANG_IDNOISE_MODULE self.typeFormatDict["keyword"] = SCT_LEX_ERLANG_IDNOISE.STC_ERLANG_IDNOISE_KEYWORD self.typeFormatDict["comment"] = SCT_LEX_ERLANG_IDNOISE.STC_ERLANG_IDNOISE_COMMENT self.typeFormatDict["macros"] = SCT_LEX_ERLANG_IDNOISE.STC_ERLANG_IDNOISE_MACROS self.typeFormatDict["number"] = SCT_LEX_ERLANG_IDNOISE.STC_ERLANG_IDNOISE_NUMBER def StyleText(self, event): start = self.control.GetEndStyled() end = event.GetPosition() line = self.control.LineFromPosition(start) start = self.control.PositionFromLine(line) text = self.control.GetTextRange(start, end) self.control.StartStyling(start, 0x1f) lastEnd = 0 for type, start, end, value in getHighlightRules(text): style = SCT_LEX_ERLANG_IDNOISE.STC_ERLANG_IDNOISE_DEFAULT if start > lastEnd: self.control.SetStyling(start - lastEnd, style) if type in self.typeFormatDict: style = self.typeFormatDict[type] self.control.SetStyling(len(value), style) lastEnd = end class CustomSTC(stc.StyledTextCtrl): def __init__(self, parent): super(CustomSTC, self).__init__(parent) self.custlex = SCT_LEX_ERLANG_IDNOISE(self) #self.SetKeyWords(0, kwlist) self.SetLexer(stc.STC_LEX_CONTAINER) self.EnableLineNumbers() self.StyleSetSpec(stc.STC_STYLE_DEFAULT, ColorSchema.formats["other"]) self.StyleClearAll() self.StyleSetSpec(stc.STC_STYLE_LINENUMBER, ColorSchema.lineFont) self.StyleSetSpec(SCT_LEX_ERLANG_IDNOISE.STC_ERLANG_IDNOISE_DEFAULT, ColorSchema.formats["other"]) self.StyleSetSpec(SCT_LEX_ERLANG_IDNOISE.STC_ERLANG_IDNOISE_VARIABLE, ColorSchema.formats["variable"]) self.StyleSetSpec(SCT_LEX_ERLANG_IDNOISE.STC_ERLANG_IDNOISE_ATOM, ColorSchema.formats["atom"]) self.StyleSetSpec(SCT_LEX_ERLANG_IDNOISE.STC_ERLANG_IDNOISE_MODULE, ColorSchema.formats["module"]) self.StyleSetSpec(SCT_LEX_ERLANG_IDNOISE.STC_ERLANG_IDNOISE_KEYWORD, ColorSchema.formats["keyword"]) self.StyleSetSpec(SCT_LEX_ERLANG_IDNOISE.STC_ERLANG_IDNOISE_COMMENT, ColorSchema.formats["comment"]) self.StyleSetSpec(SCT_LEX_ERLANG_IDNOISE.STC_ERLANG_IDNOISE_MACROS, ColorSchema.formats["macros"]) self.StyleSetSpec(SCT_LEX_ERLANG_IDNOISE.STC_ERLANG_IDNOISE_NUMBER, ColorSchema.formats["number"]) # Event Handlers self.Bind(stc.EVT_STC_STYLENEEDED, self.OnStyle) def EnableLineNumbers(self, enable=True): """Enable/Disable line number margin""" if enable: self.SetMarginType(1, stc.STC_MARGIN_NUMBER) self.SetMarginMask(1, 0) self.SetMarginWidth(1, 35) else: self.SetMarginWidth(1, 0) def OnStyle(self, event): if self.custlex: self.custlex.StyleText(event) else: event.Skip()
MemoryError on dictionary variable Question: What is wrong with my code that executinon in 3rd round of `nfind` (while loop), return MemoryError in line with `CACHE[sha] = number`? On system there is enough memory, and on the every end of the while loop I clear allocated memory, but it returns error in the 3rd run through `while` loop. If you run these code, in some cases on, I suppose it is necessary to change `XRAN= 2**23` to greater, or smaller exponent (by one or two), to produce error. Please help and suggestions. from multiprocessing import Pool from hashlib import sha256 from struct import pack import gc XRAN= 2**23 def compsha(number): return number, sha256(pack("Q", number)).digest() if __name__ == '__main__': gc.enable() nfind = 1 while (nfind > 0): print(nfind) CACHE = {} pool = Pool() for i, output in enumerate(pool.imap_unordered(compsha, xrange((nfind-1)*XRAN, nfind*XRAN), 2)): number, sha = output CACHE[sha] = number pool.close() pool.join() if nfind != 0 : nfind = nfind + 1 del CACHE ======================================================= >>> 1 2 Traceback (most recent call last): File "D:\Python27\free_pool.py", line 20, in <module> CACHE[sha] = number MemoryError Answer: In addition to Ned's answer about storing way too much in a dictionary that you don't even use, is it possible that you are running on a 32-bit python interpreter and hitting a 4GB memory limit in your main process? $ python -c "import sys; print sys.maxint" // 64-bit python 9223372036854775807 $ python-32 -c "import sys; print sys.maxint" // 32-bit 2147483647 On windows, a 32-bit process might be limited between 2-4GB
Generating Links to Youtube Audio Question: I have been for a while now, as part of a larger project, trying to find a way to stream Youtube AUDIO into an application without downloading the corresponding file. What I have as of now is a program that downloads the video using a web service such as [saveyoutube.com](http://saveyoutube.com/). This, however is not very efficient. The downloading of the video itself takes around 5 minutes, and the client may get tired of waiting and just use the Youtube interface directly. Also, say the user of the program wishes to access a 4-hour long album. However, they want to listen only to a specific part of it, for sake of explanation, lets say the user wants to see the video from 2 hours onwards (for example, take [this](https://developers.google.com/youtube/) video). There is no doubt that my program works for this as well, but it takes approximately 20 minutes for the music to start playing (as downloading 2 hours of audio takes alot of time). Also, I have used up around 400 megabytes of space on the user’s computer by then. Sure, I can store the file in a temporary folder and delete it after they close the program, but that leads to more problems: 1. If the program crashes at 1 minute before the download is complete because of lack of space (who knows what the client has on their computer), the client would have wasted around 20 minutes of their time for nothing. 2. Say the next time they load the program, they wish to do the same thing. Then they have to wait ANOTHER 20 minutes. This could be countervented by adding a 'Save Audio' button to the interface, which would keep the program from deleting the file when it closes. However, the first impass remains. So here is my question: is there a way to generate links to the AUDIO of Youtube videos? Is there a way to obtain a url like <http://www.youtube.com/watch?v=AOARzA8nGu4.(AUDIOEXTENSION>)? That way skipping to a part in the soundtrack would be easier, and would not require downloading. I have researched this for quite a while, and so far, the closest thing to an answer WAS saveyoutube: a mp3 downloader. Is this even possible to do? If not, is there an alternative to Youtube that this can be done to? I have looked into the [Youtube API](https://developers.google.com/youtube/), but that again is unfavorable, as like most Google services, its API is limited. Programming language is not a limitation, as most code can be translated. However, a Python or C/C++ solution would be ideal. Thanks in advance! P.S. I have a server available for this, but I would be very reluctant to download all Youtube videos onto the server. However, if there is another solution involving a server that does not involve ripping off the entirety of Youtube, that would be great. Answer: After a considerable amount of more research, I found a solution. While not obtaining LINKS to the audio, I created a program that plays the YouTube video invisibly, and hence can play the 'AUDIO', which was my intention. The program I wrote uses alot of the already available Python modules to achieve the goal. I found [this](http://www.daniweb.com/software- development/python/threads/64949/write-a-flash-player-by-python) link, which explains how to embed Flash into a Python application, via wxPython (found [here](http://www.wxpython.org)). It has a activexwrapper module, which I utilized to play the Flash. Code: import wx if wx.Platform == '__WXMSW__': from wx.lib.flashwin import FlashWindow class MyPanel(wx.Panel): def __init__(self, parent, id): wx.Panel.__init__(self, parent, -1) self.pdf = None sizer = wx.BoxSizer(wx.VERTICAL) btnSizer = wx.BoxSizer(wx.HORIZONTAL) self.flash = FlashWindow(self, style=wx.SUNKEN_BORDER) sizer.Add(self.flash, proportion=1, flag=wx.EXPAND) #sizer.Hide(0) self.SetSizer(sizer) self.SetAutoLayout(True) print "Importing Flash..." self.flash.LoadMovie(0, raw_input('Copy link for flash: ')) #Used to load a flash file. You may also give a location of a specific file on disk. print "Done." app = wx.PySimpleApp() # create window/frame, no parent, -1 is default ID, title, size # change size as needed frame = wx.Frame(None, -1, "Flash Stream", size = (500, 400)) # make instance of class, -1 is default ID MyPanel(frame, -1) # show frame frame.Show(True) #comment if you don't want to see the ui print "Started" # start event loop app.MainLoop() That plays the video. In my case, I did not want to have the GUI, so I deleted the '`frame.Show(True)`' line. If you wish to test it, try a link like '[http://www.youtube.com/v/cP6lppXT-9U?version=3&hl=en_US](http://www.youtube.com/v/cP6lppXT-9U?version=3&hl=en_US)', as I will explain later. However, this does not allow for pausing, etc. Therefore, other methods must be used. To start autoplay: add a '`&autoplay=1`' to the URL Here is how you can pause: You can generate the video length uring the [youtube- dl](http://rg3.github.com/youtube-dl/download.html) module, and kill the thread when the user pauses it. However, you would store the time already played, and the next time, you would add a '`&start=SECONDSPLAYED`', which will effectively 'resume' the video. Details on this are found [here](http://www.mydigitallife.info/youtube-allows-you-to-start-playing- embed-video-at-specific-start-time/). Also, you MUST use the YouTube embed url, which is the only one that works. An example looks like '`http://www.youtube.com/v/cP6lppXT-9U?version=3&hl=en_US`' **Pros** * Legal* * Fast Flash Loading Time (0.01 seconds benchmark) * Does not waste space * Can skip to ending without downloading entire file * Unlimited uses, due to not using the YouTube API *According to [YouTube's terms of service](http://www.youtube.com/static?gl=US&template=terms), section 4: General Use of the Service—Permissions and Restrictions, subsection 3. > You agree not to access Content through any technology or means other than > the video playback pages of the Service itself, the Embeddable Player, or > other explicitly authorized means YouTube may designate. Due to that the program uses an alternate interface that mainly uses the Embeddable Player, and does not do anything outright illegal (like downloading the file [my first idea]). **Cons** * Due to the reliance on ActiveX, this application will **NOT** work on any operating system BUT Windows. * From the people I know, few use Internet Explorer. Alas, this program requires the INTERNET EXPLORER Flash to be installed; not Mozzila Flash, Chrome Flash. It absolutely HAS to be IE. Otherwise, the application will load, but the video will not appear. * wx takes a VERY long time to load (approx 10 seconds). **Dependencies** * For obvious reasons, wxPython must be used. * Python comtypes (found [here](http://pypi.python.org/pypi/comtypes)) must be installed. Otherwise, wxPython cannot communicate with ActiveX. **Helpful Functions** I also created some functions to speed up the process for anyone who is doing the same thing. All are nice one-liner lambdas. generate_link: returns the YouTube Embed URL, given a normal YouTube URL. generate_link = lambda link: 'http://www.youtube.com/v/'+re.compile(r'watch\?v=(.*?)(?:&|$)').search(link).group(1)+'?version=3&amp;hl=en_US' start_from: Accepts the hour, minute, and seconds of where to start a video, and returns a link. start_from = lambda hours, minutes, seconds, link: link + '&start=' + str((hours*60*60)+(minutes*60)+seconds) autoplay: Probably the simplest, sets autoplay to true, and returns a link. It accepts a link. autoplay = lambda link: link + '&autoplay=1' video_length: Returns the length of the video. Useful, accepts YouTube link. video_length = lambda video: re.compile(r'length_seconds=(.*?)\\', re.S).search(urllib2.urlopen(video).read()).group(1).strip() This is meant as a workaround for the fact that licensed videos will return an error status=fail&errorcode=150&reason=This+video+contains+content+from+WMG.+It+is+restricted+from+playback+on+certain+sites.%3Cbr%2F%3E%3Cu%3E%3Ca+href%3D%27http%3A%2F%2Fwww.youtube.com%2Fwatch%3Fv%3DVALbSjayAgw%26feature%3Dplayer_embedded%27+target%3D%27_blank%27%3EWatch+on+YouTube%3C%2Fa%3E%3C%2Fu%3E Therefore, I parsed the actual video page to get the length. A bit slower, but works without fail.
Structuring a fabric project with namespaces Question: I use fabric more and more frequently now, and I love it. So far, my fabric scripts tend to be relatively short and ad-hoc. It gets the job done and it's fine. That's what I like about it compared to more elaborate tools out there. I am now trying to bunch together a collection of scripts and want to make them more accessible and easy to use. [Namespaces](http://docs.fabfile.org/en/1.4.1/usage/tasks.html#namespaces) seems like the way to go and it looks simple and elegant. Currently, the missing piece of the puzzle for me is where to place various **templates and configuration files** that different fabric tasks need (and some might share), and also how to **share functions or tasks** between submodules. Do I need to set up some `PYTHONPATH` or modify the system's path to make those accessible from all submodules? Is there a recommended structure (or a best-practice guide) for building such fabric project? Answer: I mostly use regular python imports to accomplish this. For example, if your directory structure is this: mytoplevel/ ├── __init__.py ├── mydeploymenttasks.py └── templates ├── __init__.py └── mytemplate.mak Your template can be obtained using something like this: import pkg_resources pkg_resources.resource_filename('mytoplevel.templates',mytemplate.mak) But since tasks live in regular python modules, you can simply import them using your package's structure: from mytoplevel.mydeploymenttasks import installApplicationTask As to how you would structure your package, this depends on its domain. If you find a certain topic grows in your code, break it off into it's own module.
Python - IOError: [Errno 13] Permission denied: Question: Im getting IOError: [Errno 13] Permission denied, i dont know what im doing wrong. Im trying to read a file given an absolute path (meaning only file.asm), and a relative path (meaning /.../file.asm) and i want the program to write the file to whatever path is given - if it is absolute, it should write it to the current dir. otherwise, to the path given. the code: #call to main function if __name__ == '__main__': assem(sys.argv[1]) import sys def assem(myFile): from myParser import Parser import code from symbolTable import SymbolTable table=SymbolTable() #max size of each word WORD_SIZE = 16 #rom address to save to rom_addrs = 0 #variable address to save to var_addrs = 16 #new addition if (myFile[-4:] == ".asm"): newFile = myFile[:4]+".hack" output = open(newFile, 'w') <==== ERROR the error given: IOError: [Errno 13] Permission denied: '/Use.hack' the way i execute the code : python assembler.py Users/***/Desktop/University/Add.asm what am i doing wrong over here? Answer: **Just Close the opened file where you are going to write.**
How to add drop down list for timezone using python-TZ at user registration page using UserCreationForm class Question: I want to add a Drop down list showing common timezone using PYtZ package at the time of user registration page. To register an user i am using UserCreationForm class. Code as follow: class UserRegisterForm(UserCreationForm): email2 = forms.EmailField(label=_("E-mail")) def clean_email2(self): email2 = self.cleaned_data['email2'] try: user = User.objects.get(email=email2) except User.DoesNotExist: return email2 raise forms.ValidationError(_("Account with this e-mail address already exists.")) def save(self, commit=True): user = super(UserRegisterForm, self).save(commit=False) user.email = self.cleaned_data["email2"] user.is_active = False if commit: user.save() return user I am getting the list of all common timezone using following command: >>> from pytz import timezone >>> import pytz >>> print(pytz.common_timezones) it prints: <http://pastebin.com/RHdie16M> I am also aware of the choices fields but to use that is not a good idea. What should i do? Answer: You could use a choicefield as such: timezone = forms.ChoiceField(choices=[(x, x) for x in pytz.common_timezones])
Python threading: how to use return values of external scripts? Question: (I found a decent solution [here](http://stackoverflow.com/questions/5093164/multi-threading-different- scripts "here") for this, but unfortunately I'm using IronPython which does not implement the mutliprocessing module ...) Driving script Threader.py will call Worker.py's single function twice, using the threading module. Its single function just fetches a dictionary of data. Roughly speaking: **Worker.py** def GetDict(): : : : return theDict **Threader.py** import threading from Worker import GetDict : : : def ThreadStart(): t = threading.Thread(target=GetDict) t.start() : : In the driver script Threader.py, I want to be able to operate on the two dictionaries outputted by the 2 instances of Worker.py. The accepted answer [here](http://stackoverflow.com/questions/2577233/threading-in-python- retrieve-return-value-when-using-target/ "here") involving the Queue module seems to be what I need in terms of accessing return values, but this is written from the point of view of everthing being doen in a _single_ script. How do I go about making the return values of the function called in Worker.py available to Threader.py (or any other script for that matter)? Many thanks Answer: another way to do what you want (without using a `Queue`) would be by using the [`concurrent.futures`](http://docs.python.org/dev/library/concurrent.futures.html) module (from python3.2, for earlier versions [there is a backport](http://pypi.python.org/pypi/futures)). using this, your example would work like this: from concurrent import futures def GetDict(): return {'foo':'bar'} # imports ... # from Worker import GetDict def ThreadStart(): executor = futures.ThreadPoolExecutor(max_workers=4) future = executor.submit(GetDict) print(future.result()) # blocks until GetDict finished # or doing more then one: jobs = [executor.submit(GetDict) for i in range(10)] for j in jobs: print(j.result()) if __name__ == '__main__': ThreadStart() edit: something similar woule be to use your own thread to execute the target function and save it's return value, something like this: from threading import Thread def GetDict(): return {'foo':'bar'} # imports ... # from Worker import GetDict class WorkerThread(Thread): def __init__(self, fnc, *args, **kwargs): super(WorkerThread, self).__init__() self.fnc = fnc self.args = args self.kwargs = kwargs def run(self): self.result = self.fnc(*self.args, **self.kwargs) def ThreadStart(): jobs = [WorkerThread(GetDict) for i in range(10)] for j in jobs: j.start() for j in jobs: j.join() print(j.result) if __name__ == '__main__': ThreadStart()
Python - Office Communicator API - Is it possible to send messages despite restrictions Question: I've messed around with a number of Office programs using win32com in Python. Excel has been useful and Outlook was simple to satisfy my basic use needs. I have Microsoft Lync and I'm having trouble using it. I know there are restrictions but what I would like to do is; send a message, detect received messages and reply. I have used the below code to open a new window: import win32com.client msg = win32com.client.Dispatch('Communicator.UIAutomation') msg.InstantMessage('[email protected]') This works fine to open a messenger window but any methods to send a message generally raise a "Not implemented" error. I know the api is restricted but I was wondering whether it is even possible to send message this way or detect received messages, or is there another way of communicating with Communicator? I don't really want to use a SendKeys method to write a message. Any help will be appreciated. Answer: Instead of trying to drive the Communicator GUI program, you might want to consider implementing an interface to the underlying chat protocol. Communicator can speak the [XMPP protocol](http://en.wikipedia.org/wiki/Extensible_Messaging_and_Presence_Protocol) \- the same as Google Talk, Facebook Chat, etc. From Wikipedia: > Furthermore, several enterprise IM software products that do not natively > use XMPP nevertheless include gateways to XMPP, including: > > * IBM Lotus Sametime > * Microsoft Lync Server (formerly named Microsoft Office Communications > Server – OCS) > You should be able to implement your own XMPP client. [`libpurple`](http://developer.pidgin.im/wiki/WhatIsLibpurple), the chat protocol library behind [Pidgin](http://www.pidgin.im/), implements XMPP; you could use this if you wanted to.
concurrent.futures ThreadPoolExecutor fails to wait? Question: I am trying to get a script performance improved, using ThreadPoolExecutor from concurrent.futures. I am launching some external python scripts via Popen and encapsulating them as a future objects, but these objects enter the callback function as finished, but I can see them running on my machine (they run for quite some minutes). The code looks like this: with futures.ThreadPoolExecutor(max_workers=4) as executor: p1 = executor.submit(subprocess.Popen([myotherPythonscript1], stdout = subprocess.PIPE)) p1.add_done_callback(process_result) p2 = executor.submit(subprocess.Popen([myotherPythonscript2], stdout = subprocess.PIPE)) p2.add_done_callback(process_result) def process_result( future ): logger.info( "Seeding process finished...") I also tried different approaches with running() and wait() future functions, but with the same results. Future objects are marked as already done, but in fact they are still running. Am I missing something? Thanks, Answer: you can't just pass the result of `Popen` to your executor, you have to pass a callable. >>> from concurrent.futures import * >>> from subprocess import * >>> executor = ThreadPoolExecutor(4) >>> future = executor.submit(Popen(['echo', 'test'], stdout=PIPE)) >>> future.exception() TypeError("'Popen' object is not callable",) this on the other hand works: from concurrent.futures import * from subprocess import * def make_call(): process = Popen(['echo', 'test'], stdout=PIPE) return process.communicate()[0] executor = ThreadPoolExecutor(4) future = executor.submit(make_call) print(future.result())
Killing python ffmpeg subprocess breaks cli output Question: I'm trying to execute a system command with subprocess and reading the output. But if the command takes more than 10 seconds I want to kill the subprocess. I've tried doing this in several ways. My last try was inspired by this post: <http://stackoverflow.com/a/3326559/969208> Example: import os import signal from subprocess import Popen, PIPE class Alarm(Exception): pass def alarm_handler(signum, frame): raise Alarm def pexec(args): p = Popen(args, stdout=PIPE, stderr=PIPE) signal.signal(signal.SIGALRM, alarm_handler) signal.alarm(10) stdout = stderr = '' try: stdout, stderr = p.communicate() signal.alarm(0) except Alarm: try: os.kill(p.pid, signal.SIGKILL) except: pass return (stdout, stderr) The problem is: After the program exits no chars are shown in the cli until I hit return. And hitting return will not give me a new line. I suppose this has something to do with the stdout and stderr pipe. I've tried flushing and reading from the pipe (p.stdout.flush()) I've also tried with different Popen args, but might've missed something. Just thought I'd keep it simple here. I'm running this on a Debian server. Am I missing something here? EDIT: It seems this is only the case when killing an ongoing ffmpeg process. If the ffmpeg process exits normally before 10 seconds, there is no problem at all. I've tried executing a couple of different command that take longer than 10 seconds, one who prints output, one who doesn't and a ffmpeg command to check the integrity of a file. args = ['sleep', '12s'] # Works fine args = ['ls', '-R', '/var'] # Works fine, prints lots for a long time args = ['ffmpeg', '-v', '1', '-i', 'large_file.mov','-f', 'null', '-'] # Breaks cli output I believe ffmpeg prints using \r and prints everything on the strerr pipe. Can this be the cause? Any ideas how to fix it? Answer: Well. your code surely works fine on my Ubuntu server. (which is close cousin or brother of Debian I suppose) I added few more lines, so that I can test your code. import os import signal from subprocess import Popen, PIPE class Alarm(Exception): pass def alarm_handler(signum, frame): raise Alarm def pexec(args): p = Popen(args, stdout=PIPE, stderr=PIPE) signal.signal(signal.SIGALRM, alarm_handler) signal.alarm(1) stderr = '' try: stdout, stderr = p.communicate() signal.alarm(0) except Alarm: print "Done!" try: os.kill(p.pid, signal.SIGKILL) except: pass return (stdout, stderr) args = ('find', '/', '-name','*') stdout = pexec(args) print "----------------------result--------------------------" print stdout print "----------------------result--------------------------" Works like a charm. If this code works on your server, I guess problem actually lies on command line application that you trying to retrieve data.
performance issue : big numpy array and system call Question: There is a performance issue when using a system call after pre-allocating big amount of memory (e.g. numpy array). The issue grows with the amount of memory. test.py : import os import sys import time import numpy start = time.clock() test = int(sys.argv[1]) a = numpy.zeros((test,500,500)) for i in range(test) : os.system("echo true > /dev/null") elapsed = (time.clock() - start) print(elapsed) The per-iteration time increases dramatically : edouard@thorin:~/now3/code$ python test.py 100 0.64 edouard@thorin:~/now3/code$ python test.py 200 2.09 edouard@thorin:~/now3/code$ python test.py 400 14.26 This should not be related to virtual memory. Is it a known issue? Answer: You seem to have narrowed the problem down to `os.system()` taking longer after you've allocated a large NumPy array. Under the covers, `system()` uses [`fork()`](http://en.wikipedia.org/wiki/Fork_%28operating_system%29). Even though `fork()` is supposed to be very cheap (due to its use of [copy-on- write](http://en.wikipedia.org/wiki/Copy-on-write)), it turns out that things are not quite as simple. In particular, there are known issues with Linux's `fork()` taking longer for larger processes. See, for example: * [Faster forking of large processes on Linux?](http://stackoverflow.com/questions/2731531/faster-forking-of-large-processes-on-linux) * [Linux Fork Performance Redux: Large Pages](http://kirkwylie.blogspot.co.uk/2008/11/linux-fork-performance-redux-large.html). Both documents are fairly old, so I am not sure what the state of the art is. However, the evidence suggests that you've encountered an issue of this sort. If you can't get rid of those `system()` calls, I would suggest two avenues of research: * Look into enabling huge pages. * Consider the possibility of spawning an auxiliary process on startup, whose job would be to invoke the necessary `system()` commands.
extracting specific content from html page Question: Suppose I have an html page source like: <p><font face="Arial" color="#400040"><small><strong> <a href="some_link">description</a>: </strong>some text.</small></font></p> I want to just extract the "description part? How do I do this. I think there is a very pythonic way to do this. Thanks Answer: Get [BeautifulSoup](http://www.crummy.com/software/BeautifulSoup/). Then: from BeautifulSoup import BeautifulSoup soup = BeautifulSoup(your_text) description = soup.find('a').string You may need to modify the last line to uniquely identify your a tag.
Python path issue while importing my own modules. What is the best way to go about it? Question: I've created python modules but they are in different directories. /xml/xmlcreator.py /tasklist/tasks.py Here, tasks.py is trying to import xmlcreator but both are in different paths. One way to do it is include xmlcreator.py in the Pythonpath. But, considering that I'll be publishing the code, this doesn't seem the right way to go about it as suggested [here](http://stackoverflow.com/questions/279237/python- import-a-module-from-a-folder). Thus, how do I include xmlcreator or rather any module that might be written by me which would be in various directories and sub directories? Answer: Are you going to publish both modules separately or together in one package? If the former, then you'll probably want to have your users install your xml module (I'd call it something else :) so that it is, by default, already on Python's path, and declare it as a dependency of the tasklist module. If both are distributed as a bundle, then [relative imports](http://docs.python.org/tutorial/modules.html#intra-package- references) seem to be the best option, since you can control where the paths are relative to each other.
Will this work? hex edited a file and changed inet_aton to inet_pton Question: I am trying to port a python script to an old Solaris 10 machine. I downloaded and installed all the required packages from sunfreeware. It crashed in the import line (import CGIHTTPServer) with this error message: > ImportError: ld.so.1: python: fatal: relocation error: file > /usr/local/lib/python2.6/lib-dynload/_socket.so: symbol inet_aton: > referenced symbol not found I tried to recompile with libresolve, but I didn't want to do that, so I copied the file _socket.so to my linux machine and edited with ghex2. I replaced the inet_aton with inet_pton because i read that solaris uses inet_pton instead. I've also read in [python documentation that both system calls are similar](http://docs.python.org/release/2.5.2/lib/module- socket.html). I copied back the file _socket.so to the original dir, backed up the old one and replaced with the patched one. It's running and looks OK so far. Do you think the python socket module will break in the future? Do `inet_aton` and `inet_pton` return structs compatible? Answer: No; `inet_aton` and `inet_pton` are not compatible. Just look at the prototypes: int inet_aton(const char *, struct in_addr *); int inet_pton(int, const char *, void *); Totally different. Trying to swap one for the other will only result in pain and suffering (and a crash, most likely). If you've done this and it seems to be working, it's probably because the code which uses `inet_aton` isn't being called.
Makefile on python Question: I'm trying to write a Makefile for a python script, that will create a `VMTranslator` executable file, which is supposed to get an input, meaning this is how it is supposed to be done on shell commands: 1)make <==== should make the VMTranslator executable. 2)VMTranslator BasicTest.vm <==== the user is supposed to use it like this. i have tried the following according to what i have found online: #!/usr/local/bin/ python *$ but it is not working. the files needed to be included are: codeWriter.py , vmTranslator.py , parser.py . how can this be done? Answer: The Python binary is an interpreter. It does not create stand-alone executables. What you can do is to write a Python script that does what you want, as long as the Python executable is present the script can be made to run transparently: #!/usr/bin/env python # import codeWriter import vmTranslator import parser # Add code here to parse arguments and call into the imported code. Save that as `VMTranslator`, and make the file executable (`chmod +x VMTranslator`).
How to store lat-lon geolocation point in a document for GAE search? Question: There where indications in the [GoogleIO talk on Search API](http://youtu.be/7B7FyU9wW8Y?t=26m10s) that we can do searches based on geolocation. I can't find an [appropriate field](https://developers.google.com/appengine/docs/python/search/fieldclasses) to store location info. How can I store geolocation info in the [document](https://developers.google.com/appengine/docs/python/search/documentclass) so I could issue queries based on distance from a particular GPS location? Answer: On June 28, 2012, Google integrated the [GeoPoint class](https://developers.google.com/appengine/docs/python/search/geopointclass) into the Google App Engine Search API library with the specific intent of making spatial points searchable. GeoPoints are stored as GeoFields within the Search Document. Google provides [this support documentation](https://developers.google.com/appengine/docs/python/search/overview#Performing_Location- Based_Searches) outlining the use of the GeoPoint with the Search API. The following example declares a GeoPoint and assigns it to a GeoField in a Search Document. These new classes provide a lot more functionality than what is listed below, but this code is a starting point for a basic understanding of how to use the new spatial search functionality.. **Constructing a document with an associated GeoPoint** ## IMPORTS ## from google.appengine.api import search def CreateDocument(content, lat, long): geopoint = search.GeoPoint(lat, long) return search.Document( fields=[ search.HtmlField(name='content', value=content), search.DateField(name='date', value=datetime.now().date()) search.GeoField(name='location', value=geopoint) ]) **Searching the GeoPoint document field (Slightly modified from the Search API docs)** ## IMPORTS ## from google.appengine.api import search ndx = search.Index(DOCUMENT_INDEX) loc = (-33.857, 151.215) query = "distance(location, geopoint(-33.857, 151.215)) < 4500" loc_expr = "distance(location, geopoint(-33.857, 151.215))" sortexpr = search.SortExpression( expression=loc_expr, direction=search.SortExpression.ASCENDING, default_value=4501) search_query = search.Query( query_string=query, options=search.QueryOptions( sort_options=search.SortOptions(expressions=[sortexpr]))) results = index.search(search_query)
Does win32security.LogonUser() Update Last Logon Timestamp? Question: I'm writing a Python script that will automatically logon users from a list. This script will be run once a month to prevent accounts from being disabled due to low activity. Below is the working code: import win32security import getpass accounts = {'user1':'password1', 'user2':'password2', 'user3':'password3'} for username, password in accounts.items(): handle = win32security.LogonUser(username, "DOMAIN", password, win32security.LOGON32_LOGON_INTERACTIVE, win32security.LOGON32_PROVIDER_DEFAULT) print username.upper() + ': ' + repr(bool(handle)) handle.close() My question is, would the win32security.LogonUser() update the "last logged on" timestamp in Active Directory? Is there another way to achieve this without having administrative rights to the Active Directory server? Thanks Wole Answer: The interactive logon call you're making should update this. There's no way to manually update the value even with administrative rights, though as an FYI.
include tag not up-to-date on App Engine 1.6.5 Question: I'm running Google App Engine 1.6.5 and according to the release notes, Django 1.3 is supposed to be supported. However my {% include %} tags can't accept context parameters; I get the following error. I've checked my django version which is 1.3.1 when app engine is running locally. I was fine on Python 2.5. By the way, I am importing django using use_library('django', '1.3') and also have the following line in my app.yaml: libraries: \- name: django version: 1.3 Any ideas ? Error: line 89, in render t = _load_internal_django(template_path, debug) File "/Applications/GoogleAppEngineLauncher.app/Contents/Resources/GoogleAppEngine-default.bundle/Contents/Resources/google_appengine/google/appengine/ext/webapp/template.py", line 163, in _load_internal_django template = django.template.loader.get_template(file_name) File "/Applications/GoogleAppEngineLauncher.app/Contents/Resources/GoogleAppEngine-default.bundle/Contents/Resources/google_appengine/google/appengine/_internal/django/template/loader.py", line 160, in get_template template = get_template_from_string(template, origin, template_name) File "/Applications/GoogleAppEngineLauncher.app/Contents/Resources/GoogleAppEngine-default.bundle/Contents/Resources/google_appengine/google/appengine/_internal/django/template/loader.py", line 168, in get_template_from_string return Template(source, origin, name) File "/Applications/GoogleAppEngineLauncher.app/Contents/Resources/GoogleAppEngine-default.bundle/Contents/Resources/google_appengine/google/appengine/_internal/django/template/__init__.py", line 158, in __init__ self.nodelist = compile_string(template_string, origin) File "/Applications/GoogleAppEngineLauncher.app/Contents/Resources/GoogleAppEngine-default.bundle/Contents/Resources/google_appengine/google/appengine/_internal/django/template/__init__.py", line 186, in compile_string return parser.parse() File "/Applications/GoogleAppEngineLauncher.app/Contents/Resources/GoogleAppEngine-default.bundle/Contents/Resources/google_appengine/google/appengine/_internal/django/template/__init__.py", line 281, in parse compiled_result = compile_func(self, token) File "/Applications/GoogleAppEngineLauncher.app/Contents/Resources/GoogleAppEngine-default.bundle/Contents/Resources/google_appengine/google/appengine/_internal/django/template/loader_tags.py", line 195, in do_extends nodelist = parser.parse() File "/Applications/GoogleAppEngineLauncher.app/Contents/Resources/GoogleAppEngine-default.bundle/Contents/Resources/google_appengine/google/appengine/_internal/django/template/__init__.py", line 281, in parse compiled_result = compile_func(self, token) File "/Applications/GoogleAppEngineLauncher.app/Contents/Resources/GoogleAppEngine-default.bundle/Contents/Resources/google_appengine/google/appengine/_internal/django/template/loader_tags.py", line 173, in do_block nodelist = parser.parse(('endblock', 'endblock %s' % block_name)) File "/Applications/GoogleAppEngineLauncher.app/Contents/Resources/GoogleAppEngine-default.bundle/Contents/Resources/google_appengine/google/appengine/_internal/django/template/__init__.py", line 281, in parse compiled_result = compile_func(self, token) File "/Applications/GoogleAppEngineLauncher.app/Contents/Resources/GoogleAppEngine-default.bundle/Contents/Resources/google_appengine/google/appengine/_internal/django/template/defaulttags.py", line 693, in do_for nodelist_loop = parser.parse(('empty', 'endfor',)) File "/Applications/GoogleAppEngineLauncher.app/Contents/Resources/GoogleAppEngine-default.bundle/Contents/Resources/google_appengine/google/appengine/_internal/django/template/__init__.py", line 281, in parse compiled_result = compile_func(self, token) File "/Applications/GoogleAppEngineLauncher.app/Contents/Resources/GoogleAppEngine-default.bundle/Contents/Resources/google_appengine/google/appengine/_internal/django/template/defaulttags.py", line 828, in do_if nodelist_true = parser.parse(('else', 'endif')) File "/Applications/GoogleAppEngineLauncher.app/Contents/Resources/GoogleAppEngine-default.bundle/Contents/Resources/google_appengine/google/appengine/_internal/django/template/__init__.py", line 281, in parse compiled_result = compile_func(self, token) File "/Applications/GoogleAppEngineLauncher.app/Contents/Resources/GoogleAppEngine-default.bundle/Contents/Resources/google_appengine/google/appengine/_internal/django/template/loader_tags.py", line 210, in do_include raise TemplateSyntaxError("%r tag takes one argument: the name of the template to be included" % bits[0]) Answer: The issue was as pointed out by Guido the templating system I was using which always uses 1.2.5. The solution is to change my templating system to Django or Jinja ...
Dramatic memory leak in wxpython application Question: I'm some way into building a fairly complex wxPython app using ode for physical modelling, openGL for rendering, and wx for UI. Everything was going swimmingly until the application started to crash. After a few days of making no progress I finally noticed that my application was leaking memory. I was able to distill into a smallish example script something that leaks at a quite extraordinary rate: #------------------------------------------------------------------------------- #------------------------------------------------------------------------------- import wx import wx.propgrid as wxpg import random class CoordProperty(wxpg.PyProperty): def __init__(self, label, name, value=(0,0,0)): wxpg.PyProperty.__init__(self, label, name) self.SetValue(value) def GetClassName(self): return "CoordProperty" def GetEditor(self): return "TextCtrl" def ValueToString(self, value, flags): x,y,z = value return "%f,%f,%f"%(x,y,z) app = wx.App(False) frame = wx.Frame(None, -1, "Test") pg = wxpg.PropertyGridManager(frame) props = {} for i in range(1000): prop_name = "prop_%d"%i prop = CoordProperty("Coord", prop_name) pg.Append(prop) props[prop_name] = prop def OnTimer(event): global props for key in props: props[key].SetValue((random.random(), random.random(), random.random())) timer = wx.Timer(frame, 1) frame.Bind(wx.EVT_TIMER, OnTimer) timer.Start(10) # 100Hz frame.Show() app.MainLoop() timer.Stop() The example creates a frame, and places a wxPropertyGrid into it. It derives a property that display a 3d co-ordinate value, creates a thousand of them, and then from a timer running at 100Hz it updates each to a random value. This leaks somewhere close to 10Mb/sec, and eventually crashes. It usually crashes at shutdown too. I'm using python 2.7 & wx 2.9.3.1 msw (classic) on Windows 7. If I replace my derived CoordProperty with a built-in property, such as wxpg.FloatProperty, and modify the code accordingly, the leak goes away. Any ideas? Or should I submit a wx bug? I can even remove the definition of the function ValueToString in the derived property class and the app still leaks. Answer: I use the following code to count objects: def output_memory(): d = defaultdict(int) for o in gc.get_objects(): name = type(o).__name__ d[name] += 1 items = d.items() items.sort(key=lambda x:x[1]) for key, value in items: print key, value and found that your program will increase 1000 tuples every time event. So when you call `props[key].SetValue()` the prev value has not been collected by gc. This may be a bug of wxpg, we can walk around this bug by using `([x],[y],[z])` to save the values, so you can update the value without call the SetValue(): for name, prop in props.iteritems(): value = prop.GetValue() value[0][0] = random() value[1][0] = random() value[2][0] = random() pg.Refresh() Here is the full code: import wx import wx.propgrid as wxpg from random import random import gc from collections import defaultdict def output_memory(): d = defaultdict(int) for o in gc.get_objects(): name = type(o).__name__ d[name] += 1 items = d.items() items.sort(key=lambda x:x[1]) for key, value in items: print key, value class CoordProperty(wxpg.PyProperty): def __init__(self, label, name): wxpg.PyProperty.__init__(self, label, name) self.SetValue(([0],[0],[0])) def GetClassName(self): return "CoordProperty" def GetEditor(self): return "TextCtrl" def GetValueAsString(self, flags): x,y,z = self.GetValue() return "%f,%f,%f"%(x[0],y[0],z[0]) app = wx.App(False) frame = wx.Frame(None, -1, "Test") pg = wxpg.PropertyGridManager(frame) props = {} for i in range(1000): prop_name = "prop_%d"%i prop = CoordProperty("Coord", prop_name) pg.Append(prop) props[prop_name] = prop def OnTimer(event): for name, prop in props.iteritems(): value = prop.GetValue() value[0][0] = random() value[1][0] = random() value[2][0] = random() pg.Refresh() #output_memory() timer = wx.Timer(frame, 1) frame.Bind(wx.EVT_TIMER, OnTimer) timer.Start(10) frame.Show() app.MainLoop() timer.Stop()
Indentation Error -Python frames Question: Can someone look what is the problem with this code..Everything looks good for me but I get indentation error. The code below creates a new frame and contains a button.. WHen the button is clicked a event is triggered and displays more information about the parent and child.. Code: import wx class MyApp(wx.App): def OnInit(self): self.frame = MyFrame(None, title="The Main Frame") self.SetTopWindow(self.frame) self.frame.Show() return True class MyFrame(wx.Frame): def __init__(self, parent, id=wx.ID_ANY, title="", pos=wx.DefaultPosition, size=wx.DefaultSize, style=wx.DEFAULT_FRAME_STYLE, name="MyFrame"): super(MyFrame, self).__init__(parent, id, title, pos, size, style, name) # Attributes self.panel = wx.Panel(self) self.panel.SetBackgroundColour(wx.BLACK) self.button = wx.Button(self.panel, label="Push Me", pos=(50, 50)) self.btnId = button.GetId() # Event Handlers self.Bind(wx.EVT_BUTTON, self.OnButton, button) def OnButton(self, event): """Called when the Button is clicked""" print "\nFrame GetChildren:" for child in self.GetChildren(): print "%s" % repr(child) print "\nPanel FindWindowById:" button = self.panel.FindWindowById(self.btnId) print "%s" % repr(button) # Change the Button's label button.SetLabel("Changed Label") print "\nButton GetParent:" panel = button.GetParent() print "%s" % repr(panel) print "\nGet the Application Object:" app = wx.GetApp() print "%s" % repr(app) print "\nGet the Frame from the App:" frame = app.GetTopWindow() print "%s" % repr(frame) if __name__ == "__main__": app = MyApp(False) app.MainLoop() Here is the error: C:\Python27\wx>python frame_new.py File "frame_new.py", line 22 self.btnId = button.GetId() ^ IndentationError: unexpected indent Answer: Open the file in some program that can show tabs and spaces, such as Notepad++ on Windows. Then you can see if you have some kind of tab / space mix or something.
noob: organizing input fields in wxpython dialogs Question: I am new to wxpython so this may be a pretty easy question, I dunno. I want to have a dialog box pop up that takes user input. Check. I want multiple user input fields. Check. I also want to have them come up in the same line, e.g.: Enter the Month: _x_ Enter the Day: _x_ Enter the Hour: _x_ etc... rather than have them each take new lines. So if I have code like this (copied from some tutorial): import wx class TextFrame(wx.Frame): def __init__(self): wx.Frame.__init__(self, None, -1, 'Text Entry Example', size=(300, 100)) panel = wx.Panel(self, -1) basicLabel = wx.StaticText(panel, -1, "Basic Control:") basicText = wx.TextCtrl(panel, -1, "I've entered some text!", size=(175, -1)) basicText.SetInsertionPoint(0) pwdLabel = wx.StaticText(panel, -1, "Password:") pwdText = wx.TextCtrl(panel, -1, "password", size=(175, -1),style=wx.TE_PASSWORD) sizer = wx.FlexGridSizer(cols=2, hgap=6, vgap=6) sizer.AddMany([basicLabel, basicText, pwdLabel, pwdText]) panel.SetSizer(sizer) app = wx.PySimpleApp() frame = TextFrame() frame.Show() app.MainLoop() How would I make it so that the "basic control" and "password" fields appeared on the same line? Answer: If you want all the widgets on the same line, then change the number of columns for your sizer from 2 to 4. Or use a horizontally oriented box sizer.
Most suitable python library for Github API v3 Question: I am looking for a python library for the Github APIv3 suitable for me. Background: I am a python noob with a background primarily rooted in Matlab and C++, and have recently learned to use python-matplotlib. I found one library [(python-github3)](https://github.com/copitux/python- github3) mentioned in the [GH API docs](http://developer.github.com/v3/libraries/). After playing around with it in ipython for an hour or two, I found it really unintuitive to explore/work with. I looked some more, and found there's quite a number of people at least attempting to write such a library. The more promising-looking (at a glance) are [PyGithub](https://github.com/jacquev6/PyGithub) and [another python- github3](https://github.com/ChristopherMacGown/python-github3), which apparently is different from the first one. _Before I spend the next days consecutively trying out library after library, I wanted to ask the SO community if there is an accepted, definitive, obvious choice for that library?_ What I didn't like about the first library was the (to me) unintuitive way to get at data - some things you get as attributes, some you get as return value of a method, that return value is some complicated object which has to be paged and iterated through, etc. In that regard, PyGithub looks more attractive at first glance - clearly drill down through an object hierarchy, and then arrive at the attribute containing what you want: `for repo in g.get_user().get_repos(): print repo.name` So, any pearls of wisdom to share? I know I don't have skills enough to quickly judge library quality, which is why I'm turning to the SO community. _edit: fwiw, I ended up using**PyGithub**. It works well, and the author is really receptive for feedback and bug reports. :-)_ Answer: Since you mentioned you are a beginner python programmer, I would suggest you to try to use the JSON API without any Github library first. It really isn't that difficult and it will help you a lot later in your programming life since same approach can be applied to any JSON API. Especially if it seems that trying out libraries will take days. I'm not saying that some library isn't easier to use, I'm just saying the small extra effort to use the API directly might be worth it in the long run. At least it will help you understand why some of those libraries seem "unintuitive" (as you said). Simple example to fetch creation time of django repository: import requests import json r = requests.get('https://api.github.com/repos/django/django') if(r.ok): repoItem = json.loads(r.text or r.content) print "Django repository created: " + repoItem['created_at'] This is using the popular [requests library](http://docs.python- requests.org/en/latest/index.html). In your code you'll naturally need to handle the error cases too. If you need access with authentication it will be a bit more complex.
Deleting everything that is enclosed with quotes or is a number in Python? Question: Lets say I have this string: myString="'Hello'+yes+'Whats hello'6" I am looking for a way to delete everything enclosed in quotes So, it would become: "+yes+" Because, 'Hello' and 'Whats hello' are enclosed by quotes. And 6 is a number. Is there a way to do this? Maybe using Regular Expressions? I tried doing this with a For Loop, but I guess my logic wasn't that great. Answer: Python 2.7.2 (default, Aug 19 2011, 20:41:43) [GCC] on linux2 Type "help", "copyright", "credits" or "license" for more information. >>> import re >>> re.sub(r"('[^']*'|\d)", "", "'Hello'+yes+'Whats hello'6") '+yes+' >>> `(...|...)` matches one thing or another; `'[^']*'` matches anything but a quote inside quotes; `\d` matches digits. `re.sub(pattern, replacement, string)` replaces each instance of pattern with the replacement. ps note that the `'` in the result are just python putting quotes around the string! (you can use single or double quotes in python; python prefers single when printing strings, if the string itself doesn't contain any). **update** \- is this what you want? >>> import re >>> re.sub(r"('[^']*'|(?<![a-zA-Z])\d(?![a-zA-Z]))", "", "'Hello'+yes+'Whats hello'6") '+yes+' >>> re.sub(r"('[^']*'|(?<![a-zA-Z])\d(?![a-zA-Z]))", "", "+ye5s") '+ye5s'
hashlib.sha256 returned some weird characters in python Question: In javascript the code below returned **eec097af19ad461ac825ccce57a012543da33c986e4607475e1fe5c6dc098d0a** <script src="http://crypto-js.googlecode.com/svn/tags/3.0.1/build/rollups/hmac-sha512.js"></script> <script> var hash = CryptoJS.HmacSHA256("Message", "Secret"); </script> In python same logic returned some weird characters like �����F�%��W�T=�<�nFG^��� � import hmac import hashlib import base64 hash = hmac.new('Secret', "Message", hashlib.sha256).digest() I think they should return same hash as i have used same algorithm for both. Any suggestions ? Thanks Answer: try hexdigest() import hmac import hashlib import base64 hash = hmac.new('Secret', "Message", hashlib.sha256).hexdigest()
How to hide console with Popen on Windows? Question: I had found this topic and i found this as a solution: [Module subprocess has no attribute 'STARTF_USESHOWWINDOW'](http://stackoverflow.com/questions/4703983/module- subprocess-has-no-attribute-startf-useshowwindow) but when I run code reality differs. :/ 1. Run my code: # Get the environment variables from OO-Python using subprocess oo_py_exec = os.path.join(oo_dir, r'program\python.exe') python_oo_script = ' ;'.join([ "-cimport os", "print(os.environ['URE_BOOTSTRAP'])", "print(os.environ['UNO_PATH'])", "print(os.environ['PATH'])", ]) subprocess.STARTF_USESHOWWINDOW info = subprocess.STARTUPINFO() info.dwFlags = subprocess.STARTF_USESHOWWINDOW info.wShowWindow = subprocess.SW_HIDE process = subprocess.Popen([oo_py_exec, python_oo_script], stdout=subprocess.PIPE, startupinfo=info) result = process.communicate() Console is showed. 1. Run code from link: kwargs = {} if subprocess.mswindows: su = subprocess.STARTUPINFO() su.dwFlags |= subprocess.STARTF_USESHOWWINDOW su.wShowWindow = subprocess.SW_HIDE kwargs['startupinfo'] = su subprocess.Popen("cmd.exe", **kwargs) Console is also showed! win xp, py 2.6 Answer: You shouldn't use `python.exe` but instead `pythonw.exe` \- those are identical except one does show a console, the other does not (no idea what the `w` does stand for though).
Python version of a Perl regular expression Question: I have this Perl regular expression and I want to convert it to Python. The regex I want is a search and replace that finds text and converts it to upper case. It also must be the first occurring result. Perl regex: open FILE, "C:/thefile.txt"; while (<FILE>){ # Converts "foo yadayada bar yadayada" # to "FOO bar yadayada" s/(^.*?)(yadayada)/\U$1/; print; } The Python regex I have is not working correctly: import re lines = open('C:\thefile.txt','r').readlines() for line in lines: line = re.sub(r"(yadayada)","\U\g<1>", line, 1) print line I realize the `\U\g<1>` is what isn't working because Python doesn't support `\U` for uppercase.. so what do I use!?! Answer: `re.sub` can take a function, which processes each match object and returns a string. So you can do it like this: In [4]: def uppergrp(match): ...: return match.group(1).upper() ...: In [5]: re.sub("(yada)", uppergrp, "abcyadadef", count=1) Out[5]: 'abcYADAdef' Working with regexes in Python is less convenient, but Python programmers tend to be less keen to use regexes than Perl coders.
How to write a python package Question: I am trying to refactor my code (a bunch of core modules and some apps living in a common directory). I want to get this structure Root __init__.py Core __init__.py a.py b.py c.py AppOne __init__.py AppOne.py AppTwo __init__.py AppTwo.py AppThree __init__.py AppThree.py where `AppOne.py`, `AppTwo.py` and `AppThree.py` imports the modules `a`, `b` and `c` in the `Core` package. I don't understand how to write the `__init__.py` files and the import statements. I have read <http://docs.python.org/tutorial/modules.html> and <http://guide.python-distribute.org/creation.html>. I got errors like "Attempted relative import in non-package" or "Invalid Sintaxis" Answer: You need to add the directory of the python modules to sys path. If you have something like this Root here_using_my_module.py my_module __init__.py --> leave it empty a.py b.py c.py You need to add you module directory to sys_path //here_using_your_module.py import os, sys abspath = lambda *p: os.path.abspath(os.path.join(*p)) PROJECT_ROOT = abspath(os.path.dirname(__file__)) sys.path.insert(0,PROJECT_ROOT) import a from my_module a.do_something()
Concurrent programming in Python and Qt Question: I wrote a small program to evaluate the state of cellular automata and paint it on the screen. I have dual-core PC, so in order to increase efficiency I decided to make calculations in two threads. I made my own implementations of QThread, like so: clacc MyThread(QThread): def run(self): ... Then I'm making two instances of this class and calling them: thread1 = MyThread() thread2 = MyThread() thread1.start() thread2.start() When I opened the Task Manager, I found that they're executing one after another: thread1 first, then thread2, then thread1 again and so on. Question is: is there a way to invoke them so they will work independently, on different cores and in one moment of time, not one after another? Answer: If you use threads, you can't increase efficiency as you wish, because it won't do paarallelization. You need to do multiprocessing. To do that, you can use the mulltiprocessing module, which works like threading module : import multiprocessing class MyProcess(multiprocessing.Process): def run(self): # new process context You won't share the same context so you can't communicate directly by methods calls. I advise you to use some "message queue" system like : multiprocessing.Queue or zeromq (great great lib !). If you look at "Ventillator" zmq design pattern you'll see it do exactly what you need : paralellize workers.
dotcloud supervisord.conf file environment specification Question: <http://docs.dotcloud.com/guides/daemons/> states: Configuring The Environment You can easily modify the environment of execution of your daemon with the “directory” and “environment” directives to change the directory where the command is executed and to define additional environment variable. For example: [program:daemonname] command = php my_daemon.php directory = /home/dotcloud/current/ environment = QUEUE=*, VERBOSE=TRUE However, I'm finding my PYTHONPATH environment variable is not being set: dotcloud.yml: www: type: python db: type: postgresql worker: type: python-worker supervisord.conf: [program:apnsd] command=/home/dotcloud/current/printenv.py environment=PYTHONPATH=/home/dotcloud/current/apnsd/ printenv.py #! /home/dotcloud/env/bin/python import os print "ENVIRONMENT" print os.environ the logs: ENVIRONMENT {'SUPERVISOR_ENABLED': '1', 'SUPERVISOR_SERVER_URL': 'unix:///var/dotcloud/super visor.sock', 'VERBOSE': 'no', 'UPSTART_INSTANCE': '', 'PYTHONPATH': '/', 'PREVLE VEL': 'N', 'UPSTART_EVENTS': 'runlevel', '/': '/', 'SUPERVISOR_PROCESS_NAME': 'a pnsd', 'UPSTART_JOB': 'rc', 'PWD': '/', 'SUPERVISOR_GROUP_NAME': 'apnsd', 'RUNLE VEL': '2', 'PATH': '/usr/local/sbin:/usr/local/bin:/sbin:/bin:/usr/sbin:/usr/bin ', 'runlevel': '2', 'previous': 'N'} Do not show a modified python variable! Answer: There is a bug in Supervisor; some variables (like those containing a `/`) have to be quoted. In that case, you need: [program:apnsd] command=/home/dotcloud/current/printenv.py environment= PYTHONPATH="/home/dotcloud/current/apnsd/" (The space in `= PYTHONPATH` is not mandatory, it's just to make the file slightly more readable; the quotes around the value of `PYTHONPATH` are, however, required!) I will update dotCloud's documentation to mention this issue.
How can I calculate the average of a list of tuples in python? Question: I have a list of tuples in the format: [(security, price paid, number of shares purchased)....] [('MSFT', '$39.458', '1,000'), ('AAPL', '$638.416', '200'), ('FOSL', '$52.033', '1,000'), ('OCZ', '$5.26', '34,480'), ('OCZ', '$5.1571', '5,300')] I want to consolidate the data. Such that each security is only listed once. [(Name of Security, Average Price Paid, Number of shares owned), ...] Answer: It's not very clear what you're trying to do. Some example code would help, along with some information of what you've tried. Even if your approach is dead wrong, it'll give us a vague idea of what you're aiming for. In the meantime, perhaps numpy's `numpy.mean` function is appropriate for your problem? I would suggest transforming your list of tuples into a numpy array and then applying the mean function on a slice of said array. That said, it does work on any list-like data structure and you can specify along which access you would like to perform the average. <http://docs.scipy.org/doc/numpy/reference/generated/numpy.mean.html> **EDIT:** From what I've gathered, your list of tuples organizes data in the following manner: (name, dollar ammount, weight) I'd start by using numpy to transform your list of tuples into an array. From there, find the unique values in the first column (the names): import numpy as np a = np.array([(tag, 23.00, 5), (tag2, 25.00, 10)]) unique_tags = np.unique(a[0,:]) # note the slicing of the array Now calculate the mean for each tag meandic = {} for element in unique_tags: tags = np.nonzero(a[0,:] == element) # identify which lines are tagged with element meandic[element] = np.mean([t(1) * t(2) for t in a[tags]]) Please note that this code is untested. I may have gotten small details wrong. If you can't figure something out, just leave a comment and I'll gladly correct my mistake. You'll have to remove '$' and convert strings to floats where necessary.
converting a time string to seconds in python Question: I need to convert time value strings given in the following format to seconds.I am using `python2.6` eg: 1.'00:00:00,000' -> 0 seconds 2.'00:00:10,000' -> 10 seconds 3.'00:01:04,000' -> 64 seconds 4. '01:01:09,000' -> 3669 seconds Do I need to use regex to do this ?I tried to use time module,but `time.strptime('00:00:00,000','%I:%M:%S')` threw ValueError: time data '00:00:00,000' does not match format '%I:%M:%S' Can someone tell me how this can be solved? Edit: I think pt =datetime.datetime.strptime(timestring,'%H:%M:%S,%f') total_seconds = pt.second+pt.minute*60+pt.hour*3600 gives the correct value..I was using the wrong module Answer: For Python 2.7: >>> import datetime >>> import time >>> x = time.strptime('00:01:00,000'.split(',')[0],'%H:%M:%S') >>> datetime.timedelta(hours=x.tm_hour,minutes=x.tm_min,seconds=x.tm_sec).total_seconds() 60.0
Basic python script giving Internal Server Error Question: I'm using hostgator and they swear that python is supported, but I've yet to see one working python script. I've tried several scripts, my latest one is the one they give on their website: #!/usr/bin/python print "Content-type: text/html\n\n"; print "<html><head>"; print "<title>CGI Test</title>"; print "</head><body>"; print "<p>Test page using Python</p>"; print "</body></html>"; I'm getting an Internal Server Error: <http://elkuzu.com/cgi-bin/test.py> The file has 755 permissions, so does the folder cgi-bin. They refused to help me with what they call "coding" problems... but with all that I've tried and received nothing but Internal Server Errors, I'm thinking the problem is with them. Anyone know what could be wrong? Error Logs: [Sat May 19 09:11:38 2012] [error] [client 74.129.48.242] File does not exist: /home/elkuzu/public_html/404.shtml [Sat May 19 09:11:38 2012] [error] [client 74.129.48.242] File does not exist: /home/elkuzu/public_html/favicon.ico [Sat May 19 09:11:37 2012] [error] [client 74.129.48.242] File does not exist: /home/elkuzu/public_html/500.shtml I've talked with my host (hostgator) and they've turned it into a ticket, which makes me think that something is up on their end. Answer: There is [documentation](http://docs.python.org/howto/webservers.html) on how to use Python as a CGI. In your case, the issue was the line endings. They're the hidden character at the end of each line. > On a Unix-like system, The line endings in the program file must be Unix > style line endings. This is important because the web server checks the > first line of the script (called shebang) and tries to run the program > specified there. It gets easily confused by Windows line endings (Carriage > Return & Line Feed, also called CRLF), so you have to convert the file to > Unix line endings (only Line Feed, LF). This can be done automatically by > uploading the file via FTP in text mode instead of binary mode, but the > preferred way is just telling your editor to save the files with Unix line > endings. Most editors support this. On Windows (ie Notepad) they're represented as (CR LF, or `\r\n`), whereas on unix they're (LF or `\n`). In [Notepad++](http://notepad-plus-plus.org/), you can view line endings as symbols like so: View -> Show Symbol -> Show End of Line To replace windows linebreaks with unix ones, you can use: Search -> Replace... In the replace dialogue, find `\r\n`, and replace them with `\n`. Ensure the Extended Search mode is selected. ![Notepad++ replace dialogue screenshot](http://i.stack.imgur.com/vZpwZ.png) * * * Alternatively, you can use Edit -> EOL Conversion -> UNIX Format ![Notepad++ EOL Conversion screenshot](http://i.stack.imgur.com/POxEV.png)
Efficient multiprocessing of massive, brute force maximization in Python 3 Question: This is an extension of my recent question [Avoiding race conditions in Python 3's multiprocessing Queues](http://stackoverflow.com/questions/10607747/avoiding-race-conditions- in-python-3s-multiprocessing-queues). Hopefully this version of the question is more specific. **TL;DR: In a multiprocessing model where worker processes are fed from a queue using`multiprocessing.Queue`, why are my worker processes so idle?** Each process has its own input queue so they're not fighting each other for a shared queue's lock, but the queues spend a lot of time actually just empty. The main process is running an I/O-bound thread -- is that slowing the CPU- bound filling of the input queues? I'm trying to find the maximal element of the Cartesian product of N sets each with M_i elements (for 0 <= i < N) under a certain constraint. Recall that the elements of the Cartesian product are length-N tuples whose elements are are elements of the N sets. I'll call these tuples 'combinations' to emphasize the fact that I'm looping over every combination of the original sets. A combination meets the constraint when my function `is_feasible` returns `True`. In my problem, I'm trying to find the combination whose elements have the greatest weight: `sum(element.weight for element in combination)`. My problem size is large, but so is my company's server. **I'm trying to rewrite the following serial algorithm as a parallel algorithm.** from operator import itemgetter from itertools import product # Cartesian product function from the std lib def optimize(sets): """Return the largest (total-weight, combination) tuple from all possible combinations of the elements in the several sets, subject to the constraint that is_feasible(combo) returns True.""" return max( map( lambda combination: ( sum(element.weight for element in combination), combination ), filter( is_feasible, # Returns True if combo meets constraint product(*sets) ) ), key=itemgetter(0) # Only maximize based on sum of weight ) My current multiprocessing approach is to create worker processes and feed them combinations with an input queue. When the workers receive a [poison pill](http://stackoverflow.com/questions/10607747/avoiding-race-conditions-in- python-3s-multiprocessing-queues) they place the best combination they've seen on an output queue and exit. I fill the input queue from the main thread of the main process. One advantage of this technique is that I can spawn a secondary thread from the main process to run a monitoring tool (just a REPL I can use to see how many combinations have been processed so far and how full the queues are). +-----------+ in_q0 | worker0 |----\ /-------+-----------+ \ +-----------+ in_q1 +-----------+ \ out_q +-----------+ | main |-----------| worker1 |-----------| main | +-----------+ +-----------+ / +-----------+ \-------+-----------+ / in_q2 | worker2 |----/ +-----------+ I originally had all the workers reading from one input queue but found that none of them were hitting the CPU. Figuring that they were spending all their time waiting for queue.get() to unblock, I gave them their own queues. That increased pressure on the CPU, so I figured the workers were active more often. However, the queues spend most of their time empty! (I know this from the monitoring REPL I mentioned). This suggests to me that the main loop filling up the queues is slow. Here is that loop: from itertools import cycle main(): # (Create workers, each with its own input queue) # Cycle through each worker's queue and add a combination to that queue for combo, worker in zip(product(*sets), cycle(workers)): worker.in_q.put(combo) # (Collect results and return) I'm guessing the bottleneck is `worker.in_q.put()`. How do I make that faster? My first instinct was to make the workers slower, but that just doesn't make sense... Is the problem that the monitor thread is stopping the loop too often? How would I be able to tell? Alternatively, is there another way to implement this that doesn't involve so much waiting on locks? Answer: What do your elements look like? It could be that pickling them to put them in the queue is slow, which would obviously be a bottleneck. Note that each element is being independently pickled over and over and over again. If this is the case, this approach might help: * Choose a set with cardinality >= your number of workers. Ideally, it'd be much more than the number of workers. Call this set A, and assign approximately equal subsets of A to each worker. Transmit that subset to each worker. * Distribute the full contents of all sets other than A to each of the workers (probably through `pickle.dumps` once and then transmitting the same string to each worker, or possibly through shared memory or whatever else). * Then each worker has the full information it needs to do its subset. It can start on its merry way over `product(my_A_subset, *other_sets)` (possibly ordered differently), polling for some kind of stop signal between each job (or every three jobs or whatever). This doesn't need to be through a queue, a one-bit shared-memory value works fine.
Referencing file from method in python Question: I need some help with this. I am using this method to help me open a file with a dialog box: from Tkinter import * import tkFileDialog fileOpen = Tk() fileOpen.withdraw() #hiding tkinter window file_path = tkFileDialog.askopenfilename( title="Open file", filetypes=[("txt file",".txt"),("All files",".*")]) if file_path != "": print "you chose file with path:", file_path else: print "you didn't open anything!" print file_path It works fine, and the file is opened in Python, but I don't know how to make further commands on that file, for example if I wanted to read it or write on it. I have tried referencing it as fileOpen, but that doesn't seem to work, and I have no idea what the variable would be instead. Answer: The file is not opened at all. To open it, call `open(file_path)`. That gives you an object your can `read` from or `write` to. Please read the Python tutorial's [section on file I/O](http://docs.python.org/tutorial/inputoutput.html#reading-and-writing- files).
How to disable text shaking when I click a button? Question: I am working with buttons in Tkinter, python. The thing is when I click in one button the text of the button shakes. It might be a default behavior for this widget and I don't know how to disable it and make it static. Does anyone know how to fix this? Answer: I assume that you mean the relief change from raised to sunken when you click a button. This is what I found on <http://wiki.tcl.tk/1048> (click 'Show Discussion' to see it): > Unfortunately, the relief used when you click is hardcoded (as 'sunken'), so > you can't configure it per-widget without hacking the Tk internals for the > binding for buttons. So the simplest way around this would be to always make the button appear sunken MyButton = Tkinter.Button( self.frame, text = "Foobar", command = self.foobar, relief=Tkinter.SUNKEN ) The disadvantage of that is that it might make the button look unresponsive. You can also use a widget other than a button to be used as a clickable item (suggested by Joel Cornett). Here is a simple example with a label used as a button: import Tkinter class main: def __init__(self,root): # make a label with some space around the text self.lbl1 = Tkinter.Label(root, width = 16, height = 4, text = "Foobar") self.lbl1.pack() # Call a function when lbl1 is clicked # <Button-1> means a left mouse button click self.lbl1.bind("<Button-1>", self.yadda) self.lbl1.bind("<Enter>", self.green) self.lbl1.bind("<Leave>", self.red) def yadda(self, event): self.lbl1.config(text="Clicked!") def green(self, event): self.lbl1.config(bg="green") def red(self,event): self.lbl1.config(bg="red") if __name__ == "__main__": root = Tkinter.Tk() main(root) root.mainloop()