如何向 Python 交互式 shell 添加命令?

发布于 2024-09-28 23:11:04 字数 1367 浏览 13 评论 0原文

对于我经常在 Python 中输入的命令,我试图节省自己的敲击次数。

在我的 python 启动脚本 中,我定义了一个名为 load 的函数,它类似于导入,但添加了一些功能。它需要一个字符串:

def load(s):
  # Do some stuff
  return something

为了调用这个函数,我必须输入

>>> load('something')

我宁愿能够简单地输入:

>>> load something

我正在运行Python readline 支持,所以我知道那里存在一些可编程性,但我不知道使用它是否可以实现这种功能。

我尝试通过使用 InteractivConsole 并在启动文件中创建它的实例来解决这个问题,如下所示:

import code, re, traceback

class LoadingInteractiveConsole(code.InteractiveConsole):
  def raw_input(self, prompt = ""):
    s = raw_input(prompt)
    match = re.match('^load\s+(.+)', s)
    if match:
      module = match.group(1)
      try:
        load(module)
        print "Loaded " + module
      except ImportError:
        traceback.print_exc()
      return ''
    else:
      return s

console = LoadingInteractiveConsole()
console.interact("")

这与我必须按 Ctrl-D 两次才能退出 python 解释器的警告一起工作:一次离开我的自定义控制台,一次离开真实的控制台。

有没有一种方法可以做到这一点,而无需编写自定义 C 程序并将解释器嵌入其中?

编辑

频道外,我建议将其附加到启动文件的末尾:

import sys
sys.exit()

它工作得很好,但我仍然对替代解决方案感兴趣。

I'm trying to save myself just a few keystrokes for a command I type fairly regularly in Python.

In my python startup script, I define a function called load which is similar to import, but adds some functionality. It takes a single string:

def load(s):
  # Do some stuff
  return something

In order to call this function I have to type

>>> load('something')

I would rather be able to simply type:

>>> load something

I am running Python with readline support, so I know there exists some programmability there, but I don't know if this sort of thing is possible using it.

I attempted to get around this by using the InteractivConsole and creating an instance of it in my startup file, like so:

import code, re, traceback

class LoadingInteractiveConsole(code.InteractiveConsole):
  def raw_input(self, prompt = ""):
    s = raw_input(prompt)
    match = re.match('^load\s+(.+)', s)
    if match:
      module = match.group(1)
      try:
        load(module)
        print "Loaded " + module
      except ImportError:
        traceback.print_exc()
      return ''
    else:
      return s

console = LoadingInteractiveConsole()
console.interact("")

This works with the caveat that I have to hit Ctrl-D twice to exit the python interpreter: once to get out of my custom console, once to get out of the real one.

Is there a way to do this without writing a custom C program and embedding the interpreter into it?

Edit

Out of channel, I had the suggestion of appending this to the end of my startup file:

import sys
sys.exit()

It works well enough, but I'm still interested in alternative solutions.

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(3

爱已欠费 2024-10-05 23:11:04

你可以尝试 ipython - 它提供了一个 python shell,它允许很多事情,包括 自动括号 可以根据您的要求提供函数调用。

You could try ipython - which gives a python shell which does allow many things including automatic parentheses which gives you the function call as you requested.

秋日私语 2024-10-05 23:11:04

我认为你想要 cmd 模块。

请参阅此处的教程:
http://wiki.python.org/moin/CmdModule

I think you want the cmd module.

See a tutorial here:
http://wiki.python.org/moin/CmdModule

与往事干杯 2024-10-05 23:11:04

我不想回答我自己的问题,但还没有一个答案适用于我使用的所有 Python 版本。除了我在问题编辑中发布的解决方案(这就是我现在正在使用的)之外,还有另一个:

编辑 .bashrc 以包含以下行:

alias python3='python3 ~/py/shellreplace.py'
alias python='python ~/py/shellreplace.py'
alias python27='python27 ~/py/shellreplace.py'

然后只需移动所有 LoadingInteractiveConsole 代码写入文件 ~/py/shellreplace.py 一旦脚本执行完毕,python 将停止执行,改进后的交互式会话将是无缝的。

Hate to answer my own question, but there hasn't been an answer that works for all the versions of Python I use. Aside from the solution I posted in my question edit (which is what I'm now using), here's another:

Edit .bashrc to contain the following lines:

alias python3='python3 ~/py/shellreplace.py'
alias python='python ~/py/shellreplace.py'
alias python27='python27 ~/py/shellreplace.py'

Then simply move all of the LoadingInteractiveConsole code into the file ~/py/shellreplace.py Once the script finishes executing, python will cease executing, and the improved interactive session will be seamless.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文