标签归档:interactive

如何从Python代码放入REPL(读取,评估,打印,循环)

问题:如何从Python代码放入REPL(读取,评估,打印,循环)

有没有办法以编程方式强制Python脚本在执行过程中的任意点放入REPL,即使该脚本是从命令行启动的也是如此?

我正在编写一个快速而肮脏的绘图程序,我想从stdin或文件中读取数据,对其进行绘图,然后放入REPL中以允许对绘图进行自定义。

Is there a way to programmatically force a Python script to drop into a REPL at an arbitrary point in its execution, even if the script was launched from the command line?

I’m writing a quick and dirty plotting program, which I want to read data from stdin or a file, plot it, and then drop into the REPL to allow for the plot to be customized.


回答 0

您可以尝试使用python的交互式选项:

python -i program.py

这将执行program.py中的代码,然后转到REPL。您在program.py顶层中定义或导入的所有内容都将可用。

You could try using the interactive option for python:

python -i program.py

This will execute the code in program.py, then go to the REPL. Anything you define or import in the top level of program.py will be available.


回答 1

我经常使用这个:

def interact():
    import code
    code.InteractiveConsole(locals=globals()).interact()

I frequently use this:

def interact():
    import code
    code.InteractiveConsole(locals=globals()).interact()

回答 2

这是您的操作方法(IPython> v0.11):

import IPython
IPython.embed()

对于IPython <= v0.11:

from IPython.Shell import IPShellEmbed

ipshell = IPShellEmbed()

ipshell() # this call anywhere in your program will start IPython

您应该使用IPython,Python REPL的凯迪拉克。参见http://ipython.org/ipython-doc/stable/interactive/reference.html#embedding-ipython

从文档中:

在通常需要做一些自动的,需要大量计算的部分然后停下来查看数据,绘图等的科学计算情况下,它也很有用。打开IPython实例将为您提供对数据和函数的完全访问权限,并且您可以在完成交互式部分的操作后继续执行程序(也许以后可以根据需要多次停止)。

Here’s how you should do it (IPython > v0.11):

import IPython
IPython.embed()

For IPython <= v0.11:

from IPython.Shell import IPShellEmbed

ipshell = IPShellEmbed()

ipshell() # this call anywhere in your program will start IPython

You should use IPython, the Cadillac of Python REPLs. See http://ipython.org/ipython-doc/stable/interactive/reference.html#embedding-ipython

From the documentation:

It can also be useful in scientific computing situations where it is common to need to do some automatic, computationally intensive part and then stop to look at data, plots, etc. Opening an IPython instance will give you full access to your data and functions, and you can resume program execution once you are done with the interactive part (perhaps to stop again later, as many times as needed).


回答 3

要使用iPython和调试器功能,您应该使用ipdb

您可以使用与pdb相同的方式来使用它,除了:

import ipdb
ipdb.set_trace()

To get use of iPython and functionality of debugger you should use ipdb,

You can use it in the same way as pdb, with the addition of :

import ipdb
ipdb.set_trace()

回答 4

您可以启动调试器:

import pdb;pdb.set_trace() 

不确定您想要REPL做什么,但是调试器非常相似。

You can launch the debugger:

import pdb;pdb.set_trace() 

Not sure what you want the REPL for, but the debugger is very similar.


回答 5

我只是在自己的一个脚本中执行了此操作(它在自动化框架中运行,这是一个需要检测的巨大PITA):

x = 0 # exit loop counter
while x == 0:
    user_input = raw_input("Please enter a command, or press q to quit: ")
    if user_input[0] == "q":
        x = 1
    else:
        try:
            print eval(user_input)
        except:
            print "I can't do that, Dave."
            continue

只要将其放置在需要断点的任何地方,就可以使用与python解释器相同的语法检查状态(尽管似乎不允许您进行模块导入)。它不是很优雅,但是不需要任何其他设置。

I just did this in one of my own scripts (it runs inside an automation framework that is a huge PITA to instrument):

x = 0 # exit loop counter
while x == 0:
    user_input = raw_input("Please enter a command, or press q to quit: ")
    if user_input[0] == "q":
        x = 1
    else:
        try:
            print eval(user_input)
        except:
            print "I can't do that, Dave."
            continue

Just place this wherever you want a breakpoint, and you can check the state using the same syntax as the python interpreter (although it doesn’t seem to let you do module imports). It’s not very elegant, but it doesn’t require any other setup.


从标准输入读取密码

问题:从标准输入读取密码

场景:一个交互式CLI Python程序,需要密码。这也意味着没有GUI解决方案。

在bash中,我无需重新输入密码即可在屏幕上输入密码

read -s

Python有类似的东西吗?即

password = raw_input('Password: ', dont_print_statement_back_to_screen)

替代方法:将键入的字符替换为“ *”,然后再将其发送回屏幕(又称浏览器样式)。

Scenario: An interactive CLI Python program, that is in need for a password. That means also, there’s no GUI solution possible.

In bash I could get a password read in without re-prompting it on screen via

read -s

Is there something similar for Python? I.e.,

password = raw_input('Password: ', dont_print_statement_back_to_screen)

Alternative: Replace the typed characters with ‘*’ before sending them back to screen (aka browser’ style).


回答 0

>>> import getpass
>>> pw = getpass.getpass()
>>> import getpass
>>> pw = getpass.getpass()

回答 1

是的getpass:“不提示用户提示输入密码。”

编辑:我自己还没有玩过这个模块,所以这就是我刚准备的(不过,如果到处都找到类似的代码,不会感到惊讶):

import getpass

def login():
    user = input("Username [%s]: " % getpass.getuser())
    if not user:
        user = getpass.getuser()

    pprompt = lambda: (getpass.getpass(), getpass.getpass('Retype password: '))

    p1, p2 = pprompt()
    while p1 != p2:
        print('Passwords do not match. Try again')
        p1, p2 = pprompt()

    return user, p1

(这是Python 3.x;使用raw_input而不是input使用Python2.x。)

Yes, getpass: “Prompt the user for a password without echoing.”

Edit: I had not played with this module myself yet, so this is what I just cooked up (wouldn’t be surprised if you find similar code all over the place, though):

import getpass

def login():
    user = input("Username [%s]: " % getpass.getuser())
    if not user:
        user = getpass.getuser()

    pprompt = lambda: (getpass.getpass(), getpass.getpass('Retype password: '))

    p1, p2 = pprompt()
    while p1 != p2:
        print('Passwords do not match. Try again')
        p1, p2 = pprompt()

    return user, p1

(This is Python 3.x; use raw_input instead of input when using Python 2.x.)


Oppia-一个免费的在线学习平台,让所有人都能获得优质教育

Oppia是一个在线学习工具,任何人都可以轻松地创建和分享互动活动(称为“探索”)。这些活动模拟与导师的一对一对话,使学生能够边做边学,同时获得反馈

除了开发Oppia平台外,团队还在开发和试点一套免费有效的lessons基础数学。这些课程针对的是无法获得教育资源的学习者。

Oppia是使用Python和AngularJS编写的,构建在Google App engine之上



安装

请参阅Installing Oppia page有关完整说明,请参阅

贡献

奥皮亚项目是由社区为社区建造的。我们欢迎每个人的贡献,特别是新的贡献者。

您可以在很多方面帮助Oppia的开发,包括艺术、编码、设计和文档

支持

如果您有任何功能请求或错误报告,请将它们记录在我们的issue tracker

请将安全问题直接报告给admin@oppia.org

许可证

Oppia代码在Apache v2 license

保持联系

我们在Gitter上也有公共聊天室:https://gitter.im/oppia/oppia-chat顺便过来打个招呼!