【问题标题】:How can I permanently store commands in the Python REPL/prompt?如何在 Python REPL/prompt 中永久存储命令?
【发布时间】:2011-08-21 00:28:54
【问题描述】:

有没有办法在 Python 中存储命令?

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

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

$ project

有没有办法存储命令,例如这样的:

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

>>> profile

无论何时/何地打开它都可以在 Python 命令提示符下工作?谢谢。

【问题讨论】:

  • (如果这是您唯一的用例,您可以查看来自django-extensionsshell_plus 命令)

标签: python django read-eval-print-loop


【解决方案1】:

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

export PYTHONSTARTUP=~/.python_rc.py

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

在该文件中,您可以 define a function 获取要保存的命令。在您的情况下,您所做的实际上比看起来要复杂一些,因此您需要多使用几行代码:

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

【讨论】:

  • 模块不是在“函数内部”导入的。确实,模块的名称只绑定在当前范围内,但没有什么能阻止函数将名称添加到globals
  • @Wooble:我已经避免使用global,以至于我忘记了它是可能的。好主意,补充道。
【解决方案2】:

我推荐使用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。

【讨论】:

    【解决方案3】:

    有点。

    将您的“个人资料”写成脚本并保存在某处。

    创建一个执行 Python 解释器的 shell 脚本,如下所示:

    python -i myprofile.py
    

    当您执行 shell 脚本时,它将执行文件 myprofile.py 并随后启动解释器。

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

    def do_stuff(x):
        print(x)
    

    然后运行你的 shell 脚本“快捷方式”,你可以这样做:

    >>> do_stuff(1)
    1
    

    【讨论】:

    • 好像我误解了这个问题。
    • 其实我不认为这是对这个问题的一个坏答案。这比他要求的要好——我怀疑他真的总是想要那些别名,现在看起来就是这样。
    【解决方案4】:

    不要使用 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 的解决方案很好,但它需要您为每个别名编写比此方法更多的代码;任何一个都可以。

    【讨论】:

      猜你喜欢
      • 2020-10-09
      • 2021-11-30
      • 2015-08-24
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多