I have the following piece of python code. The code is supposed to get a source, a temporary and an final output path from the user and extract some header files. When the full paths are specified from the terminal, the program works perfectly but when the terminal command is as so :
Python Get-iOS-Private-SDKs.py 开发者_StackOverflow社区-p /Developer/Platforms/iPhoneOS.platform/Developer/SDKs/iPhoneOS4.3.sdk/System/Library/PrivateFrameworks/ -t ./tmp -f ./Test.txt
, then the header files, instead of getting generated in a tmp folder in the current directory, they go into a recursive loop. Each folder in-turn has a tmp folder and it goes on and on. Can anyone tell me why ?
import optparse,os,subprocess
from glob import glob
parser = optparse.OptionParser()
parser.add_option("-p","--path", help = "Source path", dest = "Input_Path", metavar = "PATH")
parser.add_option("-t","--temp",help = "Temporary Folder Path", dest = "Temp_Path", metavar = "PATH")
parser.add_option("-f","--file",help = "Destination Path",dest ="Output_Path",metavar = "PATH")
(opts,args) =parser.parse_args()
if (opts.Input_Path is None or opts.Output_Path is None or opts.Temp_Path is None):
print "Error: Please specify the necessary paths"
else:
os.makedirs(opts.Temp_Path + "Private_SDK")
dest = opts.Temp_Path + "Private_SDK/"
for root,subFolders,files in os.walk(opts.Input_Path):
for file in files:
os.makedirs(dest + file)
os.chdir(dest + file)
command = ['/opt/local/bin/class-dump','-H',os.path.join(root,file)]
subprocess.call(command)
The folder also does not get created as Private_SDK, it gets created as tmpPrivate_SDK. Basically if I am able to get the full path from the terminal when ./tmp is mentioned, I can make the program run !
os.makedirs gets a relative path (based on ./tmp) and gets called after calls to chdir (see dest initialisation and usage)
As already said, the loop
for file in files:
os.makedirs(dest + file)
os.chdir(dest + file)
command = ['/opt/local/bin/class-dump','-H',os.path.join(root,file)]
subprocess.call(command)
is the source of this.
Instead, you should
either work with absolute paths - that requires fetching the current working directory before the said loop with
wd = os.getcwd()
and modifyingdest
in that way that you have aabsdest = os.path.join(wd, dest)
and work with this. (Besides, you should better work more withos.path.join()
instead ofdest + file
).or go always back to the "old" working directory after a subprocess call. Here, you need the
wd = os.getcwd()
part as well and need toos.chdir(wd)
afterwards.
精彩评论