3

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

Chong Onn Keat
  • 520
  • 2
  • 8
  • 19
SantoshGupta7
  • 5,607
  • 14
  • 58
  • 116

2 Answers2

0

Have you tried?

!Script.py -arg1 $variable1\ -arg2 $variable2\ 
JoeBlender
  • 49
  • 1
0

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.

Chong Onn Keat
  • 520
  • 2
  • 8
  • 19