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
(obviously I want to grep for foo
and not the literal string py_var
)
Prefix your variable names with a $
.
For example, say you want to copy a file file1
to a path stored in a python variable named dir_path
:
dir_path = "/home/foo/bar"
!cp file1 $dir_path
Note: If using Bash, keep in mind that some strings need to be quoted:
!cp file1 "$dir_path"
Wrap your variable names in {..}
:
dir_path = "/home/foo/bar"
!cp file1 {dir_path}
Its behaviour is more predictable and powerful than $..
. E.g. if you want to concatenate another string sub_dir
to your path, $
can't do that, while with {..}
you can do:
!cp file1 {dir_path + sub_dir}
Note: Again for Bash, quotes:
!cp file1 "{dir_path}"
!cp file1 "{dir_path + sub_dir}"
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