Passing IPython variables as arguments to bash commands

后端 未结 3 487
失恋的感觉
失恋的感觉 2020-12-13 12:14

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\"
!gre         


        
相关标签:
3条回答
  • 2020-12-13 12:30

    As @Catbuilts points out, $'s are problematic. To make it more explicit and not bury the key example, try the following:

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

    And you get:

    afile.txt
    /Users/user/Documents/adir
    /Users/user/Documents/adir/{afile}
    /Users/user/Documents/adir/afile.txt
    
    0 讨论(0)
  • 2020-12-13 12:42

    Prefix your variable names with a $.

    Example

    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

    EDIT

    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}
    

    EDIT 2

    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

    0 讨论(0)
  • 2020-12-13 12:49

    You cans use this syntax too:

    path = "../_data/"
    filename = "titanicdata.htm"
    ! less {path + filename}
    
    0 讨论(0)
提交回复
热议问题