Python subprocess.call-向subprocess.call添加变量
我正试图用Python编写一个简单的程序,从我的下载文件夹中获取所有音乐文件,并将它们放在我的音乐文件夹中。我使用的是Windows,可以使用cmd提示符移动文件,但出现以下错误: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
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)