如何调用从另一个python文件返回列表的python文件?

时间:2018-04-11 12:41:47

标签: python

**File1**
`#!/usr/bin/python

import sys
import os
import ConfigParser
import re


def main(argv):
    pFilepath = "/tmp/system.conf"
    values=[]
    if not os.path.isfile(pFilepath):
        print("File path {} does not exist. Exiting...".format(pFilepath))
        sys.exit()  
    config = ConfigParser.RawConfigParser()
    config.read(pFilepath)
    for i in range(len(sys.argv)-1):    
        parts=re.split('[:]',sys.argv[i+1])
        try:
            values.append(config.get(parts[0], parts[1]))
            #print (config.get(parts[0], parts[1]))
        except:
            print parts[1],' is not present in ',parts[0]

    return values


if __name__ == '__main__':  
    print main(sys.argv[1:])`

我必须运行一个python file1,它从另一个python file2返回一个列表。是否可以在file2中存储从file1返回的列表? 从文件2我必须运行文件1。 文件1返回列表。 我必须得到该列表并将其存储在第二个文件的列表中。

文件2

`#!/usr/bin/python

import sys
import os
import ConfigParser
import subprocess
import re
import string


def main():
    pFilepath = "/tmp/system.conf"
    values=[]
    if not os.path.isfile(pFilepath):
        print("File path {} does not exist. Exiting...".format(pFilepath))
        sys.exit()  
    vals = subprocess.call('python ./utility.py Environment_P1:name Environment_P2:id', stdout = subprocess.PIPE, shell=True)
    #proc=pipe.communicate()[0]
    #vals=re.split('[,]',proc)
    for i in range(len(vals)):
        vals[i]=string.replace(vals[i],'[','')
        vals[i]=string.replace(vals[i],']','')
        vals[i]=string.replace(vals[i],"'",'')
        vals[i]=string.strip(vals[i])
        print vals[i]

if __name__ == '__main__':  
   main()`

1 个答案:

答案 0 :(得分:0)

您可以将file1.py导入file2.py。下面的示例显示了两种可以在.py文件之间返回列表的方法。您可以从函数返回列表,也可以访问file2中的变量,因为您import File1.py进入了#file1.py def get_list(): return [1,2,3,4] lst=[5,6,7,8]

File1中:

#file2.py
import file1
print(file1.get_list())
print(file1.lst)

文件2:

class BanqueViews(FormView):

def get(self, request,*args,**kwargs):
    #form=SubmitUrlForm()
    if request.user.is_active :
        current_user = request.user
        #form=FormBanque()
        form1=banqueInfo()
        form2=AjoutBanque()
        formset = BanqueFormSet()
        context={"formset":formset,"current_user":current_user,"form2":form2,"form1":form1}
        return render(request,"appOne/banquemineFormsPy.html", context)

def post(self,request,*args,**kwargs):
    current_user = request.user.id
    if request.method == "POST":
        p=int(request.POST['numpiece'])
        print(p)
        formset = BanqueFormSet(request.POST)
        form1=banqueInfo(request.POST,request.FILES);
        nom=request.POST['banque_name']
        rib=request.POST['banque_rib']
        if form1.is_valid():
            tmp=banque.objects.get(nom=nom,rib=rib)# bank name+rib should be unique
            print(tmp)
            bq=releve_bancaire(id_banque_id=tmp.id) # 
            bq.save()
            for f in formset:
                if f.is_valid():
                    cln=f.cleaned_data
                    id_fac=facture
                    tier="";
                    montantcred=f.cleaned_data.get('montantcred')
                    montantdeb=f.cleaned_data.get('montantdeb')
                    typeTiers=f.cleaned_data.get('typeTiers')
                    if typeTiers=="Client":
                        id_tier=client.objects.get(nom=cln.get('tiers'))
                        tier=id_tier.nom
                        id_fac=facture.objects.get(numfac=cln.get('numfacture').numfac,id_client_id=id_tier.id,type_fact="vente")
                    elif typeTiers=="Fournisseur":
                        id_tier=fournisseur.objects.get(nom=cln.get('tiers'))
                        #print(id_tier.id)
                        tier=id_tier.nom
                        id_fac=facture.objects.get(numfac=cln.get('numfacture').numfac,id_fournisseur_id=id_tier.id,type_fact="achat")
                    else:
                        tier=cln.get('tiers')
                        print(tier)

                    if montantdeb!=None and montantcred==None :
                        print("debitnot null")
                        s=False 
                    elif montantcred!=None and montantdeb==None :
                        print("credit not null")
                        s=True
                    b=operation_Bancaire(id_releve=bq,id_facture=id_fac.id,montantdeb=f.cleaned_data.get('montantdeb'),montantcred=f.cleaned_data.get('montantcred'),sens_operation=s,type_tiers=f.cleaned_data.get('typeTiers'),tiers=tier,date_operation=f.cleaned_data.get('dateOperation'),designation=f.cleaned_data.get("designation"))
                    b.save()
                    print('type de facture')
                    print(type(id_fac.type_fact))

                else: 
                    print("nooooott")
        else :
            print("form1 not valid")
    else:
        formset = forms.BanqueFormSet(request.POST or None) 

    context={"formset":formset,"form1":form1}
    return render(request,"appOne/banquemineFormsPy.html",context)