Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Passing options to Python executable in non-interactive mode

Tags:

python

I would like to pass some options to Python (version 2.6) every time, not just in interactive mode. Is there a file I can put such commands in?

EDIT: Specifically, I'm wanting to silence the Deprecation warnings.

like image 430
chiggsy Avatar asked Oct 16 '25 11:10

chiggsy


2 Answers

The #!/usr/bin/python line at the beginning of a Python script under Linux can be used to also pass options to the interpreter.

There are also a number of modules imported whenever Python starts up. On my system, a likely candidate for modification to set options in the manner suggested by other posters are here:

/usr/lib/python2.6/site-packages/sitecustomize.py

If you simply put this code in that file:

import warnings
warnings.simplefilter("ignore", DeprecationWarning)

it will turn off deprecation warnings for everything always, which may not be what you want. You could instead put in code that would check your own PYTHONNODEPRECATIONWARNING environment variable so you had more control.

After finding a reference to sitecustomize.py in Dive Into Python and this reference to the sitecustomize module in the Python 2.6 documentation, I think that file is your best bet for what you want. In Python 2.6, with its user specific site-packages directory it's possible to set this up on a per-user basis, though you may want to find any system-wide sitecustomize.py file and either copy it into yours or find a way to explicitly import it in yours.

like image 174
Omnifarious Avatar answered Oct 18 '25 00:10

Omnifarious


Most of the options can be passed in as environment variables -- do python -h to see the list:

$ py26 -h|grep PYTH
-B     : don't write .py[co] files on import; also PYTHONDONTWRITEBYTECODE=x
-d     : debug output from parser; also PYTHONDEBUG=x
-E     : ignore PYTHON* environment variables (such as PYTHONPATH)
         if stdin does not appear to be a terminal; also PYTHONINSPECT=x
-O     : optimize generated bytecode slightly; also PYTHONOPTIMIZE=x
-s     : don't add user site directory to sys.path; also PYTHONNOUSERSITE
-u     : unbuffered binary stdout and stderr; also PYTHONUNBUFFERED=x
-v     : verbose (trace import statements); also PYTHONVERBOSE=x
PYTHONSTARTUP: file executed on interactive startup (no default)
PYTHONPATH   : ':'-separated list of directories prefixed to the
PYTHONHOME   : alternate <prefix> directory (or <prefix>:<exec_prefix>).
PYTHONCASEOK : ignore case in 'import' statements (Windows).
PYTHONIOENCODING: Encoding[:errors] used for stdin/stdout/stderr.

Are you concerned with other flags that can't be set via environment variables?

PS the PYTHONINSPECT=x is the equivalent of -i (the grep cut that info because it comes on the immediately previous line;-).

like image 44
Alex Martelli Avatar answered Oct 18 '25 00:10

Alex Martelli