如何将命令永久存储在Python REPL/提示符中?



是否有方法在Python中存储命令?

例如,要存储bash命令,我可以输入:

# in .bash_profile
alias myproject="cd /path/to/my/project"
$ project

是否有一种存储命令的方法,例如像这样:

'store' profile="from userprofile.models import Profile"
>>> profile

将在Python命令提示符中工作,无论何时/无论何地打开它?谢谢你。

在Bash中,我假设您在.profile.bash_rc或类似的文件中定义了这些别名。在该文件中,添加

export PYTHONSTARTUP=~/.python_rc.py

这将允许您创建一个.python_rc.py文件,当您在Python提示符/REPL中启动会话时包含该文件。(在运行Python脚本时不会包含它,因为这样做可能会造成干扰。)

在该文件中,可以为要保存的命令定义一个函数。在你的情况下,你所做的实际上是一个比看起来更复杂的触摸,所以你需要使用更多的行:

def profile():
    global Profile
    import sys
    if "path/to/your/project" not in sys.path:
        sys.path.append("path/to/your/project")
    from userprofile.models import Profile

这样做之后,您将能够在Python提示符中调用profile()导入Profile

我推荐使用IPython,它在很多方面都优于标准解释器,在这种特殊情况下,您可以利用它保存宏的能力:

In [1]: from userprofile.models import Profile
In [2]: macro profile 1 # profile being the name of the macro, 1 being the line to use
Macro `profile` created. To execute, type its name (without quotes).
=== Macro contents: ===
from userprofile.models import Profile
In [3]: profile # you can now use your macro

宏也可以跨多行,macro some_macro 11 13将是一个有效的多行宏。Django的manage.py shell命令会自动使用IPython,如果IPython可用的话。

Kinda.

把你的"profile"写成一个脚本并保存到某个地方。

创建一个shell脚本,像这样执行Python解释器:

python -i myprofile.py

当你执行shell脚本时,它会执行myprofile.py文件,然后启动解释器。

如果你有一个文件myprofile.py:

def do_stuff(x):
    print(x)
然后运行shell脚本"shortcut",你可以这样做:
>>> do_stuff(1)
1

不要使用exec,这是不好的和错误的

然而,我认为你需要它来做你想做的事。

  1. 创建Python脚本。添加像

    这样的行
    # pythonprofile.py
    profile = "from userprofile.models import Profile"
    
  2. 创建一个指向脚本的PYTHONSTARTUP环境变量。这将导致代码在解释器启动时在解释器中执行。

  3. 然后实际使用命令do

    exec(profile) # Don't ever do this with code you don't trust. 
    

在当前作用域内执行字符串profile中包含的代码。exec是危险的,所以要小心。

编辑: @Jeremy的解决方案是好的,但它需要你为每个别名编写比这个方法更多的代码;

最新更新