I am writing a script that needs to call an external command using the subprocess
module. The problem is I need to pass a file provided by the user to the command so it looks similar to this:
p = subprocess.run("command arg1 arg2 {userfile}".format(userfile=f),
capture_output=True, text=True, shell=True)
I have to run the command with shell=True
to make it work and that's why I pass the command as string instead of list.
The problem is that someone may pass a file named: somefile && rm -rf ~
, which is a vaild file name for a weird reason (at least on windows. don't know about mac/linux), and then bad things happen.
Therefore, I need to escape the user input before passing it to the shell. I wanted to use the built in shlex.quote
function for this, so with the above example I get: 'somefile && rm -rf ~'
and the command becomes: command arg1 arg2 'somefile && rm -rf ~cmd'
which should work on unix systems. The problem is this escaping doesn't work on windows with the command prompt so my script fails on my windows machine.
Is there a built in or third party function/library that can escape command line arguments properly for all platforms, or at least for windows (because shlex.quote
works on unix)?
I am developing on windows so I need this script to work on this platform and I don't thing that something like "{userfile}"
is good enough.
Any solution for python 3 would be appreciated.