[英]IPython notebook: using quotes(') and dollar($) to pass string variable as argument to python script in command-line(!) | eg: abc.py -arg1 '$var1'
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但是当我使用笔记本单元中的命令行运行 python 脚本时,我会得到错误
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.经过一些试验,我发现如果一个变量是一个字符串,用引号将整个 arg 括起来就可以了。
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如果它有所作为,我正在使用 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.该命令将正常工作并且您的观察是正确的。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.