Python subprocess.call - 将变量添加到 subprocess.call

2022-01-18 00:00:00 python subprocess windowserror

问题描述

我正在尝试用 Python 编写一个简单的程序,该程序从我的下载文件夹中获取所有音乐文件并将它们放入我的音乐文件夹中.我使用的是 Windows,可以使用 cmd 提示符移动文件,但出现此错误:

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: [错误2]系统找不到指定的文件

这是我的代码:

#! /usr/bin/python

import os 
from subprocess import call

def main():
    os.chdir("C:\UsersAlexDownloads") #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()

我查看了 subprocess 库和无数其他文章,但我仍然不知道我做错了什么.

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


解决方案

subprocess.call 方法获取参数列表而不是带有空格分隔符的字符串,除非您告诉它使用 shell,即如果字符串可以包含用户输入的任何内容,则不推荐使用.

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

例如

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.

子流程文档中给出了这两种方式.

你可以传入一个分隔字符串,但是你必须让 shell 处理参数

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)

在这种情况下,移动还有一个 python 命令来执行此操作.shutil.move

Also in this case for move there is a python command to do this. shutil.move

相关文章