将IPython变量作为bash命令的参数传递 [英] Passing IPython variables as arguments to bash commands
问题描述
如何从Ipython/Jupyter笔记本执行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
(显然,我想grep表示foo
而不是文字字符串py_var
)
(obviously I want to grep for foo
and not the literal string py_var
)
推荐答案
在变量名称前加上$
.
示例
假设您要将文件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}
这篇关于将IPython变量作为bash命令的参数传递的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!