0

I have a variable toPath (contains path like C:/Program Files(x86)/bla).
This variable I pass as agrument: '[-operation update -contents ' + toPath + ']' But because I have a space in this variable I get IllegalArgumentException. How can I fix this?

Ryan M
  • 18,333
  • 31
  • 67
  • 74
Diooi
  • 55
  • 1
  • 1
  • 5
  • What exactly are you trying to do? And what does the code look like? We'll need more information than that to help you. Please edit your question. – mhlz Mar 17 '15 at 08:11
  • `toPath` is a string. Right? If it is, the cause of error you are mentioning is incorrect. Can you tell me the output for `type(toPath)`? – Moinuddin Quadri Mar 17 '15 at 08:13
  • @MoinuddinQuadri this is string – Diooi Mar 17 '15 at 08:18
  • possible duplicate of [Specifying arguments with spaces for running a python script](http://stackoverflow.com/questions/11894815/specifying-arguments-with-spaces-for-running-a-python-script) – tutuDajuju Mar 17 '15 at 08:20
  • I thin you are trying to execute this command over shell? And you are using `subprocess` module. Right? Try this: `subprocess.check_call(['-operation', 'update', '-contents', toPath])` and let me know whether it resolved the issue. – Moinuddin Quadri Mar 17 '15 at 08:26

3 Answers3

2

Pass argument in double quotes.

toPath = "\"C:/Program Files(x86)/bla\"";
Sumit Singh
  • 15,743
  • 6
  • 59
  • 89
2

I'm not sure but it looks like you are trying to do a typical newcomer mistake.

If you are trying to run a command that is build from multiple variables you can be vulnerable to injection attacks. To prevent this, use the subprocess module and hand in all parameters as a list. The module will take care of all the stuff to make it work with spaces as well.

For example ls -l should be run as:

subprocess.call(["ls", "-l"])

Your example caontains [] and might be rather different but without it would be:

subprocess.call(['-operation','update', '-contents', toPath])

Please note that there are other functions than call() (which returns the return code only) in the subprocess module.

Klaus D.
  • 13,874
  • 5
  • 41
  • 48
1

try

'[-operation update -contents "' + toPath + '"]'
amow
  • 2,203
  • 11
  • 19