ruby-on-rails - 在 jupyter notebook 中无法使用 iruby 命令

标签 ruby-on-rails ruby jupyter-notebook jupyter iruby

我在我的 jupyter 笔记本中使用 iruby,内核按预期工作并接受所有类型的 ruby​​ 语法
不幸的是 %%bash 命令导致错误。所以没有控制台命令在我的笔记本中可用。如果我切换回基本的 python 内核,%%bash 命令会按预期工作。
我怎样才能实现 bash 命令在 iruby 内核中工作?有什么我忘记安装或设置的吗?
我在 Ubuntu 20.04 中使用以下设置:
我还使用 rvm 来管理我的 ruby​​ 版本。
基本设置

sudo apt install python3-pip python3-dev
sudo -H pip3 install --upgrade pip
sudo -H pip3 install virtualenv
pip install jupyter
安装 iruby
gem install ffi-rzmq
gem install iruby --pre
iruby register --force
设置和启动
rvm use ruby-2.7.2
mkdir ~/ruby_notebook

virtualenv ~/ruby_notebook/ruby_env
source ~/ruby_notebook/ruby_env/bin/activate

jupyter notebook --notebook-dir ~/ruby_notebook
但是出现以下错误:
enter image description here
任何想法如何解决这个问题,以便我可以使用 bash 命令?
======== 更新和解决方案 ======
感谢engineersmnky,我找到了解决方案:
就像在 python notebook 中一样,我想实现以下输出:
python bash command
使用命令 %x(ls -la)我得到一个执行,但输出看起来不同
enter image description here
因此,为了获得正确的输出,我添加了以下内容:
%x(ls -la).each_line(chomp: true){|s| p s}
它接近输出,但随后是笔记本中的执行 strinfg 输出。
enter image description here
所以我的 最终解决方案 ,也是为了使执行命令不那么复杂,我现在正在使用笔记本开头的方法。
def execute_console(input)
  %x(#{input}).each_line(chomp: true){|s| p s}
  return nil
end
这样我就可以使用像这样的 rails 在我的笔记本中执行特殊命令
rails routes
execute_console('rails routes')
并且输出就像预期的一样,没有任何字符串输出。
enter image description here
语法错误也按预期打印出来。

最佳答案

要在系统级别执行命令,您可以使用以下任何命令: Kernel#system , %x (有关百分比字符串的更多信息,请参见下文),或 Kernel#` (“后记”)

system('pwd')
%x(pwd) 
`pwd`
这些都将在进程中运行并以字符串形式返回输出。
如果您希望命令在单独的进程中运行,您可以使用其他选项,例如 IO.popenfork { exec('pwd') } (如果操作系统支持)
TL;DR 为什么会发生错误
现在解释您的实际错误以及它发生的原因。
这条线不过是 %%bash ruby 正在解释它,它正在寻找一个结束 % .%是另一种创建字符串文字的方法(称为 "Percent String" )。
这种语法有趣的部分是它并没有真正定义的分隔符。 (基本上大多数非字母数字都可以打开和关闭)
%{bash}
#=> "bash" 
%(bash)
#=> "bash"
%|bash| 
#=> "bash"
文档的最后一行说明

If you are using “(”, “[”, “{”, “<” you must close it with “)”, “]”, “}”, “>” respectively. You may use most other non-alphanumeric characters for percent string delimiters such as “%”, “|”, “^”, etc.


在你的情况下 %被用作分隔符:例如
%%bash%
#=> "bash" 
但由于没有关闭%这被解释为:
%%bash
pwd 
--EOF--
因此,您收到的错误是因为 String ( "bash\npwd ) 未终止。

关于ruby-on-rails - 在 jupyter notebook 中无法使用 iruby 命令,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/65580820/

相关文章:

ruby-on-rails - Rails - 在 before_save 回调中保存另一个模型的对象

ruby - 将 Hex STDIN/ARGV/gets 转换为 ruby​​ 中的 ASCII

ruby - 我如何在 Ruby 中获得以毫秒为单位的耗时?

javascript - 是否可以为 Jupyter Notebook 包含多个自定义 js 文件?

python - 类型错误 : can only concatenate str (not "numpy.int64") to str while trying to plot the graph tree

python-3.x - 如何在 jupyter notebook markdown 中编写分段函数?

ruby-on-rails - Ruby/Rails 和 Sharepoint Web 服务

ruby-on-rails - 在 Rails 中,在哪里放置对 Controller 和模型有用的函数

ruby-on-rails - Cucumber 上的步骤定义在 Ruby on Rails 上找不到路径

c# - 用 C# 编写一个简单的 Web 服务并从 Ruby on Rails 调用它