简体   繁体   English

从终端运行python程序时添加模块

[英]Add a module when running a python program from terminal

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. 在我编写的几乎所有python代码中都非常方便。

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. 因此,我不想将行import my_errorhook添加到我编写的每个代码中,但希望自动添加此行。

I found this answer , stating that it should be avoided to change the behavior of python directly. 我找到了这个答案 ,指出应避免直接更改python的行为。 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. 并在bashrc中定义一个别名以覆盖python命令以自动添加参数。 Is there any way I could achieve such a behavior? 有什么办法可以实现这种行为?

There is no such thing like --importModule in python command line. python命令行中没有--importModule这样的东西。 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. 假设您的python文件main.py是整个程序的入口。 Now you can create another file bootstrap.py , and put below codes into the new file. 现在,您可以创建另一个文件bootstrap.py ,并将以下代码放入新文件中。

import main

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

Then the function func() can be called from all modules without being imported. 然后,可以从所有模块中调用func()函数,而无需将其导入。 For example in main.py 例如在main.py

def main():
    ...
    print(func(1))
    ...

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM