开发者

How to make a python program path independent?

from django.shortcuts import render_to_response
from django.template import RequestContext
from shapes.forms import UploadForm
import os

# TODO convert this to using ModelForm with a custom Django FileField
# For now we just stick an uploaded shapefile into a project directory

def upload(request):
    if request.method == 'POST':
        form = UploadForm(request.POST, request.FILES)
        if form.is_valid():
            form.handle(request.FILES['file_obj'])
            os.system('python ../../../automate.py') 
            #form.save() # if a modelform
            #form.cleaned_data['user'] = request.user

            return render_to_response('uploaded.html', RequestContext(request,{}))
    else:
        form = UploadForm()
    return render_to_response('upload.html', RequestContext(request,{'form': form}))

This is my code which os.system('python ../../automate.py)

and my automate.py has this

import os
os.system('python unzip.py -z data/Parking.zip -o data/')
os.system('python manage.py ogrinspect  data/Parking.shp Parking --srid=4326 --mapping --multi > output.txt')
filename='output.txt'
filename1='maps/models.py'
search="class Parking(models.Model):"
add="\n    layer_id= models.ForeignKey(Sdr_Layer)"
content=open(filename,'r').read()
content=content.replace(search,search+add)
fp=open(filename,'w')
fp.write(content)

content1=open(filename1,'r').read()

search1="layer_attribute_name = models.CharField(max_length = 100)"
add1 = "\n" + content
#print add1  
#print search1+add1
content1=content1 + add1
print content1 
fp1=open(filename1,'w')
fp1.write(content1)
fp1.close()
fp.close()

os.system('python manage.py syncdb')

Both are in completely different paths so obviously they give me errors . What I want is two things .

  1. I don't want to specify "data/Parking.shp" . It should itself get the name from the file that was uploaded and use i开发者_开发问答t in automate.py .

  2. automate.py uses the maps/models.py . Which obviously gives me an error as I am executing this file in another path . So how do I make the code independent of all this path errors .


  1. Instead of calling your unzip.py module in command line, call it directly as a python module (import unzip etc) to get the results of the unzip method. That should nedd only basic adaptations.

  2. You can get the directory of a module via its __file__ parameter, as this other SO question shows. Note that this only works in command line (python toto.py), not with IDLE for instance (this is well explained here)

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜