In using variables in the command line from a notebook cell, I saw that we can use put a $ in front of the variable, or surround the variable using {} , for example
!command {variable}
or
!command $variable
But when I was running a python script using the command line from a notebook cell, I would get errors
variable1 = '/path/to/directory'
variable2 = 7
!Script.py -arg1 $variable1 -arg2 $variable2
and
!Script.py -arg1 {variable1} -arg2 {variable2}
did not work.
After experimenting a little bit, I found that if a variable is a string, surrounding the whole arg with quotes got it to work.
variable1 = '/path/to/directory'
variable2 = 7
!Script.py -arg1 '$variable1' -arg2 $variable2
What is going on? I tried to look up this phenomena but I couldn't find anything.
If it makes a difference, I am using google colab colaboratory
你有没有尝试过?
!Script.py -arg1 $variable1\ -arg2 $variable2\
Any input line beginning with a !
character is passed verbatim(exclude the !
) to the underlying command-line interface. [source]
Passing a string variable after !
character will pass only the string content, but not the '
(quotes) symbol. You need to surround the string variable with '
(quotes) symbol in your line.
Using your example above, the two variables:
variable1 = '/path/to/directory'
variable2 = 7
When running this line:
!Script.py -arg1 $variable1 -arg2 $variable2 #wrong
it will translate to
> Script.py -arg1 /path/to/directory -arg2 7
the quotation mark is not passed to the command-line.
So, you need to add the quotation mark around the string variable:
!Script.py -arg1 '$variable1' -arg2 $variable2 #correct
that will translate to
> Script.py -arg1 '/path/to/directory' -arg2 7
the quotation mark is passed to the command-line. The command will work properly and your observation is correct.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.