Python Subprocess.call - Adding A Variable To Subprocess.call
Solution 1:
The subprocess.call
method taks a list of parameters not a string with space separators unless you tell it to use the shell which is not recommended if the string can contain anything from user input.
The best way is to build the command as a list
e.g.
cmd = ["move", "/-y", fileName, "C:\Music"]
call(cmd)
this also makes it easier to pass parameters (e.g. paths or files) with spaces in to the called program.
Both these ways are given in the subprocess documentation.
You can pass in a delimited string but then you have to let the shell process the arguments
call("move /-y "+ fileName +" C:\Music", shell=True)
Also in this case for move there is a python command to do this. shutil.move
Solution 2:
I'm not answering your question directly, but for such tasks, plumbum is great and would make your life so much easier. subprocess
's api is not very intuitive.
Solution 3:
There could be several issues:
fileName
might contain a space in it so themove
command only sees a part of filename.if
move
is an internal command; you might needshell=True
to run it:
from subprocess import check_call
check_call(r"move /-y C:\Users\Alex\Downloads\*.mp3 C:\Music", shell=True)
To move .mp3
files from Downloads folder to Music without subprocess
:
from glob import glob
from shutil import move
for path in glob(r"C:\Users\Alex\Downloads\*.mp3"):
move(path, r"C:\Music")
Post a Comment for "Python Subprocess.call - Adding A Variable To Subprocess.call"