I'm trying to run a subprocess in python but I get error message:
OSError: [Errno 13] Permission denied
cp2 = cp2.lstrip("~")
cp2 = wilixdirectory+"/Users/"+loggedusr+cp2
if cp3 == None:
subprocess.call([cp2])
else:
subprocess.call([cp2, cp3])
cp2 and cp3 are user inputs for directories
wilixdirectory is a directory
loggedusr is a string like "Bob" or "Joe"
The code is running out of Unix
Instead of assuming the path starts with a slash, and concatenating using +
, use os.path.join()
to create the path:
import os.path
basepath = os.path.join(wilixdirectory, 'Users', loggedusr)
cp2 = cp2.lstrip('~/')
cp2 = os.path.abspath(os.path.join(basepath, cp2))
if not cp2.startswith(basepath + os.path.pathsep):
# something is wrong still, the absolute final path is not inside of
# user directory, bail now.
raise ValueError('Not a valid command')
# Perhaps test if os.path.isfile(cp2) is True?
args = [cp2]
if cp3 is not None:
args.append[cp3]
subprocess.call(args)
Note that I strip ~
, and /
from the start of cp2
to remove any accidental start characters from the user input, then use os.path.abspath()
to make sure the path is a canonical path, with any ./
and ../
entries resolved. You do then need to verify that the final result is still within the users' directory and not outside of it.
You could test with os.path.isfile()
to see if the cp2
path actually points to an actual file before running subprocess.call()
.
Solution:
That would work for Linux but for Unix:
subprocess.call(["open","-a",cp2])
for Windows:
subprocess.call(["start",cp2])