这是一个令人惊讶的难以找到答案的问题。
(一些问题似乎在问至少类似的问题,例如:
但我无法从其中任何一个中得到我需要的东西。)
另外,我有点不确定我应该使用的确切术语,所以我会在这里尽量具体:
假设您在 Python shell 中使用 IDLE。
您打开了 IDLE 的文本编辑器窗口之一,其中包含脚本“example.py”。
你按下 F5,Python shell 就会出现,如果你刚刚将“example.py”中的每一行逐行输入到 shell 中,它会做的事情。
从功能上讲,这正是它所做的就是自动输入每一行,而不会因为显示它们而弄乱屏幕。(此外,每次您执行此操作时,它都会将 shell 重置为新状态,但这并不是目前真正重要的一点;有时最好选择让它不重置 shell 的状态,无论如何。 )
所以结果是现在你可以在 shell 中玩耍了,你刚刚运行的脚本中的所有函数和变量等都在那里。
但是有了irb...
我如何获得相同的效果?
例如,我irb example.rb
在 Windows 控制台中尝试过(等效的 ruby 脚本),它只是将每一行逐个输入到 irb 中,将它们喷射到屏幕上,然后自动退出到 Windows 命令提示符。
(尽管这确实按我想要的方式工作(是否有一些选项标志性的参数可以使它在这里做更多我想要的事情?),我仍然需要从文本编辑器到控制台窗口的 alt-tab , 然后输入命令和文件名, 不如直接按 F5, obvs)
为了确保我清楚我的意思,这里有一些具体的例子:
1) “example.py”的 Python 脚本 2) 在 shell 中运行它然后在 shell 中做一些事情的示例(从实际 shell 复制粘贴)
3) 一个与 Python 等效的 Ruby 脚本 4) 在repl.it的 kludgy、缓慢的在线解释器中运行它的示例,并在该 irb shell 中执行完全相同的操作(再次,复制粘贴)
1)example.py:
x = "some value you don't want to keep reassigning to this variable"
y = "some other value like that"
def some_function(var):
return "do something complicated with `"+var+"`"
print("example.py just ran")
2)Python外壳:
Python 3.2.3 (default, Apr 11 2012, 07:15:24) [MSC v.1500 32 bit (Intel)] on win32
Type "copyright", "credits" or "license()" for more information.
>>> ================================ RESTART ================================
>>>
example.py just ran
>>> x
"some value you don't want to keep reassigning to this variable"
>>> y
'some other value like that'
>>> print(some_function(x))
do something complicated with `some value you don't want to keep reassigning to this variable`
>>> x = "a frog"
>>> print(some_function(x))
do something complicated with `a frog`
>>> print("gonna run example.py again")
gonna run example.py again
>>> ================================ RESTART ================================
>>>
example.py just ran
>>> print("x is back to: `\""+x+"\"`")
x is back to: `"some value you don't want to keep reassigning to this variable"`
3)example.rb:
x = "some value you don't want to keep reassigning to this variable"
y = "some other value like that"
def some_function var
"do something complicated with `#{var}`"
end
puts "test.rb just ran"
4) repl.it上的在线 Ruby irb shell 东西:
Ruby 1.8.7 (2008-05-31 patchlevel 0) [x86-linux]
[GCC 4.2.1 (LLVM, Emscripten 1.5, Emscripted-Ruby)]
test.rb just ran
=> nil
x
=> "some value you don't want to keep reassigning to this variable"
y
=> "some other value like that"
puts some_function x
do something complicated with `some value you don't want to keep reassigning to this variable`
=> nil
x = "a frog"
=> "a frog"
puts some_function x
do something complicated with `a frog`
=> nil
puts "gonna run this script again..."
gonna run this script again...
=> nil
test.rb just ran
=> nil
puts "x is back to: `\"#{x}\"`"
x is back to: `"some value you don't want to keep reassigning to this variable"`
=> nil