How to finish sys.stdin.readlines() input?

For UNIX based systems (Linux, Mac): Hello, you can type : Ctrld Ctrld closes the standard input (stdin) by sending EOF. Example : >>> import sys >>> message = sys.stdin.readlines() Hello World My Name Is James Bond # <ctrl-d> EOF sent >>> print message [‘Hello\n’, ‘World\n’, ‘My\n’, ‘Name\n’, ‘Is\n’, ‘James\n’, ‘Bond\n’] For Windows : To … Read more

Set LD_LIBRARY_PATH before importing in python

UPDATE: see the EDIT below. I would use: import os os.environ[‘LD_LIBRARY_PATH’] = os.getcwd() # or whatever path you want This sets the LD_LIBRARY_PATH environment variable for the duration/lifetime of the execution of the current process only. EDIT: it looks like this needs to be set before starting Python: Changing LD_LIBRARY_PATH at runtime for ctypes So … Read more

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

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