在Windows 7 Pro中,我需要遍历给定位置(在本例中为Z:)的目录,并使用Python在每个目录中执行命令提示符命令。这看起来应该是直截了当的os.walk()
,但到目前为止,我所尝试的都没有奏效——我所得到的最接近的是让命令从我的桌面无限循环(该脚本如下)。我需要做些什么来完成这个任务?
import os
for root, dirs, files in os.walk("Z:/"):
for dir in dirs:
os.system('cd Z:\' + dir)
os.system('git init')
os.system('git add .')
os.system('git commit -m "Initial"')
当您运行os.system('cd WHEREVER')
时,您正在创建一个新的命令shell,该shell对当前目录有自己的想法。
当shell退出时,父进程不会保留子进程的当前目录,因此后续的os.system()
调用不会看到当前目录的任何更改。
import os
for root, dirs, files in os.walk("Z:/"):
for dir in dirs:
os.chdir('Z:\' + dir)
os.system('git init')
os.system('git add .')
os.system('git commit -m "Initial"')