python: sys is not defined

Move import sys outside of the try–except block: import sys try: # … except ImportError: # … If any of the imports before the import sys line fails, the rest of the block is not executed, and sys is never imported. Instead, execution jumps to the exception handling block, where you then try to access … 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

Get parent of current directory from Python script

Using os.path To get the parent directory of the directory containing the script (regardless of the current working directory), you’ll need to use __file__. Inside the script use os.path.abspath(__file__) to obtain the absolute path of the script, and call os.path.dirname twice: from os.path import dirname, abspath d = dirname(dirname(abspath(__file__))) # /home/kristina/desire-directory Basically, you can walk … 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?

As per the documentation: This allows you to switch from the default ASCII to other encodings such as UTF-8, which the Python runtime will use whenever it has to decode a string buffer to unicode. This function is only available at Python start-up time, when Python scans the environment. It has to be called in … 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

Hata!: SQLSTATE[HY000] [1045] Access denied for user 'divattrend_liink'@'localhost' (using password: YES)