Import from sibling directory

as a literal answer to the question ‘Python Import from parent directory‘: to import ‘mymodule’ that is in the parent directory of your current module: import os parentdir = os.path.dirname(os.path.dirname(os.path.abspath(__file__))) os.sys.path.insert(0,parentdir) import mymodule edit Unfortunately, the __file__ attribute is not always set. A more secure way to get the parentdir is through the inspect module: … Read more

Usage of sys.stdout.flush() method

Python’s standard out is buffered (meaning that it collects some of the data “written” to standard out before it writes it to the terminal). Calling sys.stdout.flush() forces it to “flush” the buffer, meaning that it will write everything in the buffer to the terminal, even if normally it would wait before doing so. Here’s some … Read more

What does sys.intern() do and when should it be used?

From the Python 3 documentation: sys.intern(string) Enter string in the table of “interned” strings and return the interned string – which is string itself or a copy. Interning strings is useful to gain a little performance on dictionary lookup – if the keys in a dictionary are interned, and the lookup key is interned, the … Read more

Capture stdout from a script?

For future visitors: Python 3.4 contextlib provides for this directly (see Python contextlib help) via the redirect_stdout context manager: from contextlib import redirect_stdout import io f = io.StringIO() with redirect_stdout(f): help(pow) s = f.getvalue()

Where is Python’s sys.path initialized from?

Python really tries hard to intelligently set sys.path. How it is set can get really complicated. The following guide is a watered-down, somewhat-incomplete, somewhat-wrong, but hopefully-useful guide for the rank-and-file python programmer of what happens when python figures out what to use as the initial values of sys.path, sys.executable, sys.exec_prefix, and sys.prefix on a normal … Read more

Why should we NOT use sys.setdefaultencoding(“utf-8”) in a py script?

tl;dr The answer is NEVER! (unless you really know what you’re doing) 9/10 times the solution can be resolved with a proper understanding of encoding/decoding. 1/10 people have an incorrectly defined locale or environment and need to set: PYTHONIOENCODING=”UTF-8″ in their environment to fix console printing problems. What does it do? sys.setdefaultencoding(“utf-8”) (struck through to … Read more