18

How to run a python with arguments that would contain spaces? I am using MacOS

For example,

>python testProgram.py argument 1 argument 2

where "argument 1" is a single argument?

ssk
  • 9,045
  • 26
  • 96
  • 169

4 Answers4

31

where "argument 1" is a single argument.

You've basically answered your own question there, "argument 1" is indeed a single argument.

In other words, you need to quote it, something like one of:

python testProgram.py "argument 1" 'argument 2'

This isn't actually a Python issue however, it depends on the shell that you're using to run the Python script.

For example, with bash, there are differences between the single and double quotes, the most important of which is probably the various expansions like $HOME - the single quoted variant does not do those expansions.

paxdiablo
  • 854,327
  • 234
  • 1,573
  • 1,953
  • What if I have sth like: RAW_PATH="/Volumes/TOSHIBA EXT/../" and I want to use $RAW_PATH as argument? This does not work for me. –  Jun 06 '17 at 14:35
  • @thigi: you would use `"${RAW_PATH}"` - variables work just fine within double quotes. – paxdiablo Jun 07 '17 at 05:50
  • Okay thank you! Sorry for not trying that, but I thought that would not work and hence I did not try it! Sorry for this inconvenience... –  Jun 07 '17 at 07:56
3

Enclose your parameters that contains spaces with double quotes

> python testProgram.py "argument 1" "argument 2"

this will work under Windows and Linux so chances are it'll be ok under Mac OS too.

Levon
  • 138,105
  • 33
  • 200
  • 191
2

Or using subprocess from within python itself:

subprocess.call(['python','testProgram.py','argument 1','argument 2'])

But the other answers are more likely to be what you want.

mgilson
  • 300,191
  • 65
  • 633
  • 696
0

Try:

>python testProgram.py "argument 1" "argument 2"
ChipJust
  • 1,376
  • 12
  • 20