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

标签 python linux python-2.7 numpy importerror

我对 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()
####

关于Python:无法导入名称/IndexError:列表索引超出范围,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31593716/

相关文章:

python - PyQt5循环问题,只有QWebEngineView对象的最后一次迭代有效

python - 正则表达式匹配联合类型的 "|"分隔值

python - Pandas:根据某些列的字符串值将数据框拆分为单独的数据框

java - 使用编程获取一张图像的R,G,B的最大值

linux - 转义引号 : `grep -w "label for=\"id_query"` does not work

python - 如何暂时忽略标点符号? Python

Python:快速下载多个文件

linux - 从日志文件中搜索值和计数

c++ - 如何在 C++ 中使用输入重定向来添加整数

Python json.loads改变对象的顺序