Want stderr in your Python program to go somewhere else? Use redirect_stderr in contextlib:
Writing a bunch to non-stdout in Python? You might want to use redirect_stdout from contextlib:
Want to print to stderr, not stdout, in a Python program? Use sys.stderr and the “file” kwarg: stdout and stderr often look identical in a terminal — but they aren’t!
Normally, “print” in Python writes to stdout. Write elsewhere with the “file” keyword argument:
Want stdout from your Python program to go elsewhere? Assign sys.stdout to a writeable file. (Don’t forget to keep the original around!) Better: print’s file kwarg.
After you import a Python module, its repr (printed representation) shows its name and the loaded file. But some modules don’t have files; they were “frozen” into Python. They have no __file__ attribute, and show “frozen” in their __loader__.
Once you import a Python module, a second import won’t reload it. That’s usually good. But what if you want to? (Common in development and debugging.) This forces the reload.
You import a Python module with the variable you’ll define, not a filename. “import mymod” tells Python to find mymod.py in each dir in sys.path. The first directory is ” (the empty string) — i.e., the directory where the program is running (i.e., not where it was defined).
Want Python to import modules in non-default dirs? You could do this: But: It doesn’t scale across many programs. And what if the dir changes? Better: Set the PYTHONPATH environment variable — scalable and set in one place.
sys.path tells Python where to look when importing a module. Think of it as a list of directories. But it also handles zipfiles. A zipfile in sys.path is treated as a directory. Files in the zipfile can be imported.