Python subprocess.call - adding a variable to subprocess.call

10,232

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

Share:
10,232

Related videos on Youtube

Beawulf
Author by

Beawulf

Updated on June 04, 2022

Comments

  • Beawulf
    Beawulf almost 2 years

    I'm trying to write a simple program in Python that takes all the music files from my Downloads folder and puts them in my Music folder. I'm using Windows, and I can move the files using the cmd prompt, but I get this error:

    WindowsError: [Error 2] The system cannot find the file specified

    Here's my code:

    #! /usr/bin/python
    
    import os 
    from subprocess import call
    
    def main():
        os.chdir("C:\\Users\Alex\Downloads") #change directory to downloads folder
    
        suffix =".mp3"    #variable holdinng the .mp3 tag
        fnames = os.listdir('.')  #looks at all files
    
        files =[]  #an empty array that will hold the names of our mp3 files
    
        for fname in fnames:  
            if fname.endswith(suffix):
                pname = os.path.abspath(fname)
                #pname = fname
                #print pname
    
                files.append(pname)  #add the mp3 files to our array
        print files
    
        for i in files:
            #print i 
            move(i)
    
    def move(fileName):
        call("move /-y "+ fileName +" C:\Music")
        return
    
    if __name__=='__main__':main()
    

    I've looked at the subprocess library and countless other articles, but I still have no clue what I'm doing wrong.

    • 9000
      9000 about 11 years
      Does not your fileName contain spaces? If it does, you have to use '"' + fileName + '"' instead, or move won't find the file.
    • eazar001
      eazar001 about 11 years
      On a sidenote, these aren't arrays, but lists
    • t-8ch
      t-8ch about 11 years
      What is the problem with [os.rename](http://docs.python.org/2/library/os.html#os.rena‌​me)