Python + PyCharm File Structure issue: AttributeEr

2019-03-01 13:34发布

问题:

I'm having the following file structure:

  • main.py
  • Crypto
    • GetGenerators.py
  • Utils
    • RecHash.py
    • ToInteger.py
    • Utils.py

GetGenerators.py looks like this:

import unittest
import os, sys
import gmpy2
from gmpy2 import mpz

sys.path.append(os.path.dirname(os.path.dirname(os.path.abspath(__file__))))
from Utils.Utils           import AssertInt, AssertClass
from Utils.ToInteger       import ToInteger
from Utils.RecHash         import RecHash    

def GetGenerators(n):
    AssertInt(n)
    assert n >= 0, "n must be greater than or equal 0"

    generators = []

    # ... irrelevant code...

    return generators


class GetGeneratorsTest(unittest.TestCase):
    def testGetGenerators(self):
        self.assertEqual(len(GetGenerators(50)), 50)


if __name__ == '__main__':
    unittest.main()

When I'm using the function GetGenerators from inside main.py, it works fine. However, when I'm running the GetGenerators.py UnitTests by rightclicking the file, "Run Unittests in GetGenerators.py", I'm getting the following error:

File "C:\Program Files (x86)\JetBrains\PyCharm 2016.3.2\helpers\pycharm\nose_helper\util.py", line 70, in resolve_name obj = getattr(obj, part)

AttributeError: 'module' object has no attribute 'GetGenerators'

I suppose it has something to do with the structure of my files, but I don't see the problem.

回答1:

I haven't had your exact problem before, but I think I've had one like it. When I use PyCharm, I find that if open and use files that I've created in a project in PyCharm, then everything works fine. I can import them, can run them; no problems. The problems I run into (which are similar to yours) are when I open a file that was not created within a PyCharm project. I can't import them, and sometimes can't even run them correctly. Maybe it's just me being stupid or maybe a real bug with PyCharm, but whatever the case is. It might be worth (if you haven't already), create a project in PyCharm and copy and paste the file contents into files you create within PyCharm. For some reason, that has worked for me in the past.