繁体   English   中英

Python:无法导入名称/ IndexError:列表索引超出范围

[英]Python: Cannot import name/IndexError: List index out of range

我对Python还是很陌生,并且我没有编写大部分代码,而只是在尝试使其工作。 我有以下两个.py文件:

这个叫做FnSim.py-

import numpy,sys, os
import math



def intFn(kVars,params): # Do not change the name of this function

sinTh = kVars['y']/(numpy.sqrt(kVars['y']**2+(1000.)**2))
I = 4*((numpy.sin((numpy.pi*.7*sinTh)/.0006)/((.7*sinTh)/.0006))**2)*numpy.cos((numpy.pi*1.2*sinTh)/.0006)**2
if not math.isnan(I):
    return I
else:
    print 'Hello'
    return 0.0
'''
sinTh = kVars['y']/(numpy.sqrt(kVars['y']**2+(params['R0'])**2))
A1 = numpy.complex(params['A1r'],params['A1i'])*numpy.e**(((-numpy.pi*params['p']*sinTh)/.0006)*1j)
A2 = numpy.complex(params['A2r'],params['A2i'])*numpy.e**(((numpy.pi*params['p']*sinTh)/.0006)*1j)
return (A1+A2)*numpy.conjugate(A1+A2)
'''
def simFn():
"""
    This is the function that will do the actual simulating. Fill out the filepaths below.
"""

nTrueDir="./data/nTrueSF.npy"#Location to save the nTrue File
inputKVDir="./data/flatY.txt"#Loaction of the Generated MC KV text File
outputWeightDir="./data/wnListSF.npy"#Location where the weighted mask file will be saved

iList = numpy.load("./data/iListSF.npy")#Location of the list of intensities. 

iMax = iList.max()
print iMax         
gS.simulate(nTrueDir,inputKVDir,outputWeightDir,iList,iMax)


from generalSim import generalSim
inputKVDir="./data/FlatY.txt"#Loaction of the Generated MC KV File(Same as above)
gS = generalSim(KVDir = inputKVDir)
if sys.argv[1] == "i":
numpy.save("./data/iListSF.npy",gS.calcIList({'A2r': 186.55622562665766, 'R0': 1000.0, 'A1r': 186.5549385015023, 'p': 1.2010987369259563, 'A2i': 0.0, 'A1i': 0.4681942082158097}))
elif sys.argv[1] == "s":
simFn()

这个叫做generalSim.py-

import numpy
import os, sys
import fileinput
from FnSim import intFn
from random import random

class generalSim (object):

def __init__(self,KVDir):
    self.KVDir = KVDir

def calcIList(self,params): 
    n = 0 
    iList = numpy.zeros(shape = (1))
    for line in fileinput.input([self.KVDir]): 
        iList.resize(n+1)       
        kvAs = line.split(",")
        kvAx = {kvA.split('=')[0]:float(kvA.split('=')[1]) for kvA in kvAs}
        iList[n] = intFn(kvAx,params)
        sys.stdout.write(str(n)+"\r")
        sys.stdout.flush()
        n+=1

    return iList

def simulate(self,nTrueDir,inputKVDir,outputWeightDir,iList,iMax):

    nTrueList = [((1.0/(iList.shape[0]))*(iList.sum(0)))]  
    numpy.save(nTrueDir,nTrueList)

    wList=iList[:]/iMax

    wnList=numpy.zeros(shape=(wList.shape[0]))

    for wn in range(len(wList)):            
        if wList[wn]>random():                
            wnList[wn] = 1 

    numpy.save(outputWeightDir,wnList)

我在标有“数据”的文件夹中还有一个名为FlatY.txt的文本文件。 FlatY.txt包含一百万行Y值。

我需要运行文件,以便创建FnSim.py中列出的.npy文件。 我不太了解Linux,但是我的目的是将文件放在“数据”文件夹中。 但是,如果我尝试编译FnSim.py,控制台将显示以下内容:

Traceback (most recent call last):

  File "FnSim.py", line 38, in <module>

    from generalSim import generalSim

  File "/home/gendreau/workspace/generalSim.py", line 5, in <module>

    from FnSim import intFn

  File "/home/gendreau/workspace/FnSim.py", line 38, in <module>

    from generalSim import generalSim

ImportError: cannot import name generalSim

当我尝试运行generalSim.py时,我得到了:

Traceback (most recent call last):

  File "generalSim.py", line 5, in <module>

    from FnSim import intFn

  File "/home/gendreau/workspace/FnSim.py", line 41, in <module>

    if sys.argv[1] == "i":

IndexError: list index out of range

有哪些解决方法可以解决这些问题并生成必要的文件?

这是一种解决方法,但请参见下文,希望对您的工作有所帮助:

因为您有很多循环导入,即第一个模块调用第二个模块,第二个模块调用第一个,依此类推,所以获得所需结果的最直接的解决方案是合并两个文件,避免循环导入:

import numpy
import os, sys
import math
import fileinput
from random import random



class generalSim (object):

    def __init__(self,KVDir):
        self.KVDir = KVDir

    def calcIList(self,params): 
        n = 0 
        iList = numpy.zeros(shape = (1))
        for line in fileinput.input([self.KVDir]): 
            iList.resize(n+1)       
            kvAs = line.split(",")
            kvAx = {kvA.split('=')[0]:float(kvA.split('=')[1]) for kvA in kvAs}
            iList[n] = intFn(kvAx,params)
            sys.stdout.write(str(n)+"\r")
            sys.stdout.flush()
            n+=1

        return iList

    def simulate(self,nTrueDir,inputKVDir,outputWeightDir,iList,iMax):

        nTrueList = [((1.0/(iList.shape[0]))*(iList.sum(0)))]  
        numpy.save(nTrueDir,nTrueList)

        wList=iList[:]/iMax

        wnList=numpy.zeros(shape=(wList.shape[0]))

        for wn in range(len(wList)):            
            if wList[wn]>random():                
                wnList[wn] = 1 

        numpy.save(outputWeightDir,wnList)


def intFn(kVars,params): # Do not change the name of this function
    sinTh = kVars['y']/(numpy.sqrt(kVars['y']**2+(1000.)**2))
    I = 4*((numpy.sin((numpy.pi*.7*sinTh)/.0006)/((.7*sinTh)/.0006))**2)*numpy.cos((numpy.pi*1.2*sinTh)/.0006)**2

    if not math.isnan(I):
        return I
    else:
        print 'Hello'
        return 0.0

'''
sinTh = kVars['y']/(numpy.sqrt(kVars['y']**2+(params['R0'])**2))
A1 = numpy.complex(params['A1r'],params['A1i'])*numpy.e**(((-numpy.pi*params['p']*sinTh)/.0006)*1j)
A2 = numpy.complex(params['A2r'],params['A2i'])*numpy.e**(((numpy.pi*params['p']*sinTh)/.0006)*1j)
return (A1+A2)*numpy.conjugate(A1+A2)
'''

def simFn():
    """
        This is the function that will do the actual simulating. Fill out the filepaths below.
    """
    nTrueDir="./data/nTrueSF.npy"#Location to save the nTrue File
    inputKVDir="./data/flatY.txt"#Loaction of the Generated MC KV text File
    outputWeightDir="./data/wnListSF.npy"#Location where the weighted mask file will be saved

    iList = numpy.load("./data/iListSF.npy")#Location of the list of intensities. 

    iMax = iList.max()
    print iMax         
    gS.simulate(nTrueDir,inputKVDir,outputWeightDir,iList,iMax)


inputKVDir="./data/FlatY.txt"#Loaction of the Generated MC KV File(Same as above)

gS = generalSim(KVDir = inputKVDir)

if sys.argv[1] == "i":
    numpy.save("./data/iListSF.npy",gS.calcIList({'A2r': 186.55622562665766, 'R0': 1000.0, 'A1r': 186.5549385015023, 'p': 1.2010987369259563, 'A2i': 0.0, 'A1i': 0.4681942082158097}))

elif sys.argv[1] == "s":
    simFn()

此外,您必须在命令行中通过传递参数is来运行此文件,或者直接从脚本中删除可忽略行:

if sys.argv[1] == "i":
    numpy.save("./data/iListSF.npy",gS.calcIList({'A2r': 186.55622562665766, 'R0': 1000.0, 'A1r': 186.5549385015023, 'p': 1.2010987369259563, 'A2i': 0.0, 'A1i': 0.4681942082158097}))

elif sys.argv[1] == "s":
    simFn()

或者,您可以按以下方式更改代码,添加一个额外的变量作为runmode并可以通过它设置实际的运行模式。

import numpy
import os, sys
import math
import fileinput
from random import random

######
run_mode = "s" # or you can change it to "i"
######

class generalSim (object):

    def __init__(self,KVDir):
        self.KVDir = KVDir

    def calcIList(self,params): 
        n = 0 
        iList = numpy.zeros(shape = (1))
        for line in fileinput.input([self.KVDir]): 
            iList.resize(n+1)       
            kvAs = line.split(",")
            kvAx = {kvA.split('=')[0]:float(kvA.split('=')[1]) for kvA in kvAs}
            iList[n] = intFn(kvAx,params)
            sys.stdout.write(str(n)+"\r")
            sys.stdout.flush()
            n+=1

        return iList

    def simulate(self,nTrueDir,inputKVDir,outputWeightDir,iList,iMax):

        nTrueList = [((1.0/(iList.shape[0]))*(iList.sum(0)))]  
        numpy.save(nTrueDir,nTrueList)

        wList=iList[:]/iMax

        wnList=numpy.zeros(shape=(wList.shape[0]))

        for wn in range(len(wList)):            
            if wList[wn]>random():                
                wnList[wn] = 1 

        numpy.save(outputWeightDir,wnList)


def intFn(kVars,params): # Do not change the name of this function
    sinTh = kVars['y']/(numpy.sqrt(kVars['y']**2+(1000.)**2))
    I = 4*((numpy.sin((numpy.pi*.7*sinTh)/.0006)/((.7*sinTh)/.0006))**2)*numpy.cos((numpy.pi*1.2*sinTh)/.0006)**2

    if not math.isnan(I):
        return I
    else:
        print 'Hello'
        return 0.0

'''
sinTh = kVars['y']/(numpy.sqrt(kVars['y']**2+(params['R0'])**2))
A1 = numpy.complex(params['A1r'],params['A1i'])*numpy.e**(((-numpy.pi*params['p']*sinTh)/.0006)*1j)
A2 = numpy.complex(params['A2r'],params['A2i'])*numpy.e**(((numpy.pi*params['p']*sinTh)/.0006)*1j)
return (A1+A2)*numpy.conjugate(A1+A2)
'''

def simFn():
    """
        This is the function that will do the actual simulating. Fill out the filepaths below.
    """
    nTrueDir="./data/nTrueSF.npy"#Location to save the nTrue File
    inputKVDir="./data/flatY.txt"#Loaction of the Generated MC KV text File
    outputWeightDir="./data/wnListSF.npy"#Location where the weighted mask file will be saved

    iList = numpy.load("./data/iListSF.npy")#Location of the list of intensities. 

    iMax = iList.max()
    print iMax         
    gS.simulate(nTrueDir,inputKVDir,outputWeightDir,iList,iMax)


inputKVDir="./data/FlatY.txt"#Loaction of the Generated MC KV File(Same as above)

gS = generalSim(KVDir = inputKVDir)

####
if run_mode == "i":
    numpy.save("./data/iListSF.npy",gS.calcIList({'A2r': 186.55622562665766, 'R0': 1000.0, 'A1r': 186.5549385015023, 'p': 1.2010987369259563, 'A2i': 0.0, 'A1i': 0.4681942082158097}))

elif run_mode == "s":
    simFn()
####

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM