Read argument with spaces in python script from shell script

How to read argument with spaces when running python script?

UPDATE

It looks like my problem is that I am calling a python script through a shell script:

It works:

> python script.py firstParam file\ with\ spaces.txt # or > python script.py firstParam "file with spaces.txt" # script.py import sys print sys.argv 

But not when I run it through a script:

myscript.sh:

 #!/bin/sh python $@ 

Fingerprints: ['firstParam', 'file', 'with', 'spaces.txt']

But I want: ['firstParam', 'file with spaces.txt']

+4
source share
2 answers

Use " $@ " instead:

 #!/bin/sh python " $@ " 

Conclusion:

 $ /tmp/test.sh /tmp/test.py firstParam "file with spaces.txt" ['/tmp/test.py', 'firstParam', 'file with spaces.txt'] 

with /tmp/test.py is defined as:

 import sys print sys.argv 
+6
source

If you want to pass parameters from a script shell to another program, you should use " $@ " instead of $@ . This ensures that each parameter will be expanded as a single word, even if it contains spaces. $@ equivalent to $1 $2 ... , and " $@ " equivalent to "$1" "$2" ...

For example, if you run: ./myscript param1 "param with spaces" :

  • $@ will be expanded to param1 param with spaces - four parameters.
  • " $@ " will be expanded to "param1" "param with spaces" - two parameters.
+4
source

Source: https://habr.com/ru/post/1414905/


All Articles