Bea*_*ulf 1 python subprocess windowserror
我正在尝试用Python编写一个简单的程序,它从我的Downloads文件夹中获取所有音乐文件并将它们放入我的Music文件夹中.我正在使用Windows,我可以使用cmd提示移动文件,但是我收到此错误:
WindowsError: [Error 2] The system cannot find the file specified
这是我的代码:
#! /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()
Run Code Online (Sandbox Code Playgroud)
我看过子进程库和无数其他文章,但我仍然不知道我做错了什么.
该subprocess.call
方法获取参数列表而不是带空格分隔符的字符串,除非您告诉它使用不推荐的shell,如果该字符串可以包含来自用户输入的任何内容.
最好的方法是将命令构建为列表
例如
cmd = ["move", "/-y", fileName, "C:\Music"]
call(cmd)
Run Code Online (Sandbox Code Playgroud)
这也使得更容易将带有空格的参数(例如路径或文件)传递给被调用程序.
这两种方式都在子流程文档中给出.
你可以传入一个分隔的字符串,但是你必须让shell处理参数
call("move /-y "+ fileName +" C:\Music", shell=True)
Run Code Online (Sandbox Code Playgroud)
同样在这种情况下移动有一个python命令来执行此操作. shutil.move