Fix Python – Passing IPython variables as arguments to bash commands


Asked By – Unni

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:

!grep py_var bar.txt

(obviously I want to grep for foo and not the literal string py_var)

Now we will see solution for issue: Passing IPython variables as arguments to bash commands


Prefix your variable names with a $.


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

from Ipython or Jupyter notebook


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}

And if you want to concatinate another string sub_dir to your path, then:

!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

This question is answered By – Unni

This answer is collected from stackoverflow and reviewed by FixPython community admins, is licensed under cc by-sa 2.5 , cc by-sa 3.0 and cc by-sa 4.0