将 IPython 变量作为参数传递给 bash 命令

Passing IPython variables as arguments to bash commands

如何从 Ipython/Jupyter 笔记本执行 bash 命令,将 python 变量的值作为参数传递,如本例所示:

py_var="foo"
!grep py_var bar.txt

(显然我想为 foo 而不是文字字符串 py_var

在您的 变量 名称前加上 $

例子

假设您要将文件 file1 复制到存储在名为 dir_pth:

的 python 变量中的路径
dir_path = "/home/foo/bar"
!cp file1 $dir_path

来自 Ipython 或 Jupyter notebook

编辑

感谢 Catbuilts 的建议,如果您想连接多个字符串形成路径,请使用 {..} 而不是 $..$。 在这两种情况下都适用的通用解决方案是坚持 {..}

dir_path = "/home/foo/bar"
!cp file1 {dir_path}

如果您想将另一个字符串 sub_dir 连接到您的路径,则:

!cp file1 {dir_path + sub_dir}

编辑 2

有关使用原始字符串(前缀为 r)传递变量的相关讨论,请参阅

您可以使用此语法来:

path = "../_data/"
filename = "titanicdata.htm"
! less {path + filename}

正如@Catbuilts 指出的那样,$ 是有问题的。为了使其更明确并且不掩盖关键示例,请尝试以下操作:

afile='afile.txt'
!echo afile
!echo $PWD
!echo $PWD/{afile}
!echo {pwd+'/'+afile}

你得到:

afile.txt
/Users/user/Documents/adir
/Users/user/Documents/adir/{afile}
/Users/user/Documents/adir/afile.txt

补充一下。就我而言,如本问题中的一些示例所示,我的参数是带空格的文件名。在那种情况下,我必须使用稍微不同的语法:"$VAR"。一个例子是

touch "file with spaces.txt"
echo "this is a line" > "file with spaces.txt"
echo "this is another line" >> "file with spaces.txt"
echo "last but not least" >> "file with spaces.txt"
echo "the last line" >> "file with spaces.txt"
cat "file with spaces.txt"

# The variable with spaces such as a file or a path
ARGUMENT="file with spaces.txt"
echo $ARGUMENT

# The following might not work
cat $pwd$ARGUMENT

# But this should work
cat $pwd"$ARGUMENT"

希望对您有所帮助。 ;)