0

I wrote a module that, if it is imported, automatically changes the error output of my program. It is quite handy to have it in almost any python code I write.

Thus I don't want to add the line import my_errorhook to every code I write but want to have this line added automatically.

I found this answer, stating that it should be avoided to change the behavior of python directly. So I thought about changing the command line, something like

python --importModule my_errorhook main.py

and defining an alias in the bashrc to overwrite the python command to automatically add the parameter. Is there any way I could achieve such a behavior?

Natjo
  • 2,005
  • 29
  • 75
  • You can define a custom python command like `python_err` or something like that and keep your `python` command too. – Ankirama Oct 12 '17 at 09:35
  • Sounds handy, but bear in mind that "Explicit is better than implicit". But I guess it's not a big deal if you don't really need to know about `my_errorhook` when reading the main code, since the errorhook only affects error output. BTW, if you use the Python REPL frequently you could add `my_errorhook` to a startup script named in PYTHONSTARTUP. – PM 2Ring Oct 12 '17 at 09:45
  • @PM2Ring That approach sounds good, too! How can I edit the PYTHONSTARTUP script? – Natjo Oct 12 '17 at 09:53
  • 1
    PYTHONSTARTUP is an environment variable, you put the name of your startup script in there, and it gets run whenever you start an interactive interpreter session in the terminal. It has no effect on scripts that aren't being run in the interactive interpreter. There's some info about it if you do `python --help` in the terminal, it's also mentioned near the start of the official tutorial. FWIW, my startup script imports `readline` and `rlcompleter` so I get full editing with history and Tab completion in the REPL. – PM 2Ring Oct 12 '17 at 10:00

1 Answers1

0

There is no such thing like --importModule in python command line. The only way you can incept the code without explicitly importing is by putting your functions in builtins module. However, this is a practice that is discouraged because it makes your code hard to maintain without proper design.

Let's assume that your python file main.py is the entry point of the whole program. Now you can create another file bootstrap.py, and put below codes into the new file.

import main

__builtins__.func = lambda x: x>=0
main.main()

Then the function func() can be called from all modules without being imported. For example in main.py

def main():
    ...
    print(func(1))
    ...
George Lei
  • 467
  • 5
  • 5