Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/python/278.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Python subprocess.call-向subprocess.call添加变量_Python_Subprocess_Windowserror - Fatal编程技术网

Python subprocess.call-向subprocess.call添加变量

Python subprocess.call-向subprocess.call添加变量,python,subprocess,windowserror,Python,Subprocess,Windowserror,我正试图用Python编写一个简单的程序,从我的下载文件夹中获取所有音乐文件,并将它们放在我的音乐文件夹中。我使用的是Windows,可以使用cmd提示符移动文件,但出现以下错误: WindowsError:[错误2]系统找不到指定的文件 这是我的密码: #! /usr/bin/python import os from subprocess import call def main(): os.chdir("C:\\Users\Alex\Downloads") #change d

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

WindowsError:[错误2]系统找不到指定的文件

这是我的密码:

#! /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()

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

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

最好的方法是将命令构建为列表

e、 g

这也使得将带有空格的参数(例如路径或文件)传递给被调用程序变得更容易

这两种方法都在中给出

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

call("move /-y "+ fileName +" C:\Music", shell=True)

在本例中,对于move,还有一个python命令来执行此操作
shutil.move

我不是直接回答你的问题,但是对于这样的任务来说,这非常好,会让你的生活变得更加轻松<代码>子流程的api不是很直观。

可能存在以下几个问题:

  • fileName
    中可能包含空格,因此
    move
    命令只能看到文件名的一部分

  • 如果
    move
    是一个内部命令;您可能需要
    shell=True
    来运行它:

  • 来自子流程导入检查\u调用
    检查通话(r“move/-y C:\Users\Alex\Downloads\*.mp3 C:\Music”,shell=True)
    
    要将
    .mp3
    文件从下载文件夹移动到音乐,无需
    子进程

    从全局导入全局
    从舒蒂尔进口
    对于glob中的路径(r“C:\Users\Alex\Downloads\*.mp3”):
    移动(路径,r“C:\音乐”)
    
    您的
    文件名是否包含空格?如果是,您必须使用
    '“+fileName+”
    ,否则
    move
    将找不到该文件。请注意,这些不是数组,而是列表
    [os.rename]有什么问题(http://docs.python.org/2/library/os.html#os.rename)
    call("move /-y "+ fileName +" C:\Music", shell=True)