Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Read argument with spaces in python script from a shell script

Tags:

python

shell

How do I read an argument with spaces when running a python script?

UPDATE:

Looks like my problem is that I'm calling the python script through a shell script:

This 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 $@

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

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

like image 467
Adam Morris Avatar asked May 29 '12 14:05

Adam Morris


2 Answers

Use "$@" instead:

#!/bin/sh
python "$@"

Output:

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

with /tmp/test.py defined as:

import sys
print sys.argv
like image 197
Martijn Pieters Avatar answered Nov 15 '22 22:11

Martijn Pieters


If you want to pass the parameters from a shell script to another program, you should use "$@" instead of $@. This will ensure that each parameter is expanded as a single word, even if it contains spaces. $@ is equivalent to $1 $2 ..., while "$@" is 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.
like image 43
interjay Avatar answered Nov 15 '22 21:11

interjay