[FIXED] Space in python variable passed as argument to subprocess

Issue

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?


Solution

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.



Answered By - Klaus D.
Answer Checked By - Katrina (Python.Easybugfix Volunteer)

Related Posts

Post a Comment