将 IPython 变量作为参数传递给 bash 命令 [英] Passing IPython variables as arguments to bash commands
问题描述
如何从 Ipython/Jupyter notebook 执行 bash 命令,将 python 变量的值作为参数传递,如本例所示:
How do I execute a bash command from Ipython/Jupyter notebook passing the value of a python variable as an argument like in this example:
py_var="foo"
!grep py_var bar.txt
(显然我想为 foo
而不是文字字符串 py_var
)
(obviously I want to grep for foo
and not the literal string py_var
)
推荐答案
使用 $
为 变量 名称添加前缀.
Prefix your variable names with a $
.
示例
假设您要将文件 file1
复制到存储在名为 dir_pth
的 python 变量中的路径:
Say you want to copy a file file1
to a path stored in a python variable named dir_pth
:
dir_path = "/home/foo/bar"
!cp file1 $dir_path
来自 Ipython 或 Jupyter 笔记本
from Ipython or Jupyter notebook
编辑
感谢 Catbuilts 的建议,如果您想连接多个字符串以形成路径,请使用 {..}
而不是 $..$
.在这两种情况下都适用的通用解决方案是坚持使用 {..}
Thanks to the suggestion from Catbuilts, if you want to concatenate multiple strings to form the path, use {..}
instead of $..$
.
A general solution that works in both situations is to stick with {..}
dir_path = "/home/foo/bar"
!cp file1 {dir_path}
如果您想将另一个字符串 sub_dir
连接到您的路径,则:
And if you want to concatinate another string sub_dir
to your path, then:
!cp file1 {dir_path + sub_dir}
编辑 2
有关使用原始字符串(以 r
为前缀)传递变量的相关讨论,请参阅 将 Ipython 变量作为字符串参数传递给 shell 命令
For a related discussion on the use of raw strings (prefixed with r
) to pass the variables, see Passing Ipython variables as string arguments to shell command
这篇关于将 IPython 变量作为参数传递给 bash 命令的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!