将 IPython 变量作为参数传递给 bash 命令
- 2025-04-16 08:56:00
- admin 原创
- 20
问题描述:
如何从 Ipython/Jupyter 笔记本执行 bash 命令,并将 python 变量的值作为参数传递,如下例所示:
py_var="foo"
!grep py_var bar.txt
(显然我想 grepfoo
而不是文字字符串py_var
)
解决方案 1:
简单情况
在变量名前添加$
。
例如,假设您要将文件复制file1
到存储在名为的 Python 变量中的路径dir_path
:
dir_path = "/home/foo/bar"
!cp file1 $dir_path
注意:如果使用 Bash,请记住某些字符串需要用引号引起来:
!cp file1 "$dir_path"
一般情况
将变量名称包装在{..}
:
dir_path = "/home/foo/bar"
!cp file1 {dir_path}
它的行为比 更可预测且更强大$..
。例如,如果你想将另一个字符串连接sub_dir
到你的路径,$
则无法做到这一点,而使用{..}
你可以这样做:
!cp file1 {dir_path + sub_dir}
注意:对于 Bash,再次引用:
!cp file1 "{dir_path}"
!cp file1 "{dir_path + sub_dir}"
原始字符串
有关使用原始字符串(以 为前缀r
)传递变量的相关讨论,请参阅将 Ipython 变量作为字符串参数传递给 shell 命令
解决方案 2:
您也可以使用这种语法:
path = "../_data/"
filename = "titanicdata.htm"
! less {path + filename}
解决方案 3:
正如@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
解决方案 4:
补充一下。就我的情况而言,正如这个问题中的一些示例所示,我的参数是带空格的文件名。在这种情况下,我必须使用稍微不同的语法:"$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"
我希望这会有所帮助。;)
相关推荐
热门文章
项目管理软件有哪些?
热门标签
曾咪二维码
扫码咨询,免费领取项目管理大礼包!
云禅道AD