首页 > 解决方案 > 导入课程时遇到问题

问题描述

我在使用 Visual Studio 19 的 Windows 10 上遇到以下问题,Python 版本为 Python 3.7.2

我正在尝试使用一个类从文本文件中获取用户名和密码以登录到 sql server。课程如下:

class LogonSql:

  def __init__(self,path):
        self.path = path
        print ('p = ' + self.path) # the class does not appear in this print


    def usr(self):

         lc = open(self.path,'r')


         up = lc.readlines()
         u = up[0]
         u = u.strip('\n')
         p = up[1]
         p = p.strip('\n')

         return u,p



#x = LogonSql.usr('g:\python_test\lib\jcd.txt')

#x = LogonSql('g:\python_test\lib\SqlLogon.txt')
#p = x.usr()

#print ('p = ' + p[1])
#print ('u = ' + p[0])

如果我在上面 5 个未注释的情况下运行该类,则它可以正常工作。

但是,当我导入该类时,我在此 python 程序中收到以下错误,我在第 11 行收到以下错误 i = LogonSql('g:\python_test\lib\SqlLogon.txt')

import pypyodbc
import mysql.connector
from mysql.connector.cursor import MySQLCursor
import ctypes
import sysconfig
import Sql_logon

print('m = ' + str(dir('Sql_logon')))


i = LogonSql('g:\python_test\lib\SqlLogon.txt') # on this line the error happens 
                # I am slso confused to where all those other methods are coming from
x = i.usr()
u = str(x[0])
p = str(x[1])

ctypes.windll.user32.MessageBoxW(0,'user  = ' + u,p,1)
con = pypyodbc.connect('DSN=mynewdsn; UID=' + u + ';PWD=' + p + ';')
cur = con.cursor()


m = ['__add__', '__class__', '__contains__', '__delattr__', '__dir__', '__doc__', '__eq__', 
'__format__', '__ge__', '__getattribute__', '__getitem__', '__getnewargs__', '__gt__', '__hash__', 
'__init__', '__init_subclass__', '__iter__', '__le__', '__len__', '__lt__', '__mod__', 
'__mul__', '__ne__', '__new__', '__reduce__', '__reduce_ex__', '__repr__', '__rmod__', '__rmul__', 
'__setattr__', '__sizeof__', '__str__', '__subclasshook__', 'capitalize', 
'casefold', 'center', 'count', 'encode', 'endswith', 'expandtabs', 'find', 
'format', 'format_map', 'index', 'isalnum', 'isalpha', 'isascii', 'isdecimal', 'isdigit', 'isidentifier', 'islower', 'isnumeric', 'isprintable', 'isspace', 'istitle', 
'isupper', 'join', 'ljust', 'lower', 'lstrip', 'maketrans', 'partition', 'replace', 'rfind', 'rindex', 'rjust', 'rpartition', 'rsplit', 'rstrip', 'split', 'splitlines', 'startswith', 'strip', 'swapcase', 'title', 'translate', 'upper', 'zfill']
Traceback (most recent call last):
  File "G:\python_test\testsql\testsql.py", line 11, in <module


NameError: name 'LogonSql' is not defined

我在上面的列表中找不到 LogonSql 类?

我在用户区 set PYTHONPATH PYTHONPATH=G:\python_test\lib 的环境变量中设置了以下内容

在 Visual Studio 中,我已将搜索路径设置为 PYTHONPATH

什么时候需要制作 *.py 代码的编译版本。我认为它不需要在 Windows 中的 dll 类别中?

我的命名约定可能需要一些注意。

谢谢杰克

标签: python

解决方案


我要你做的第一件事是检查你在LogonSql课堂上的缩进。它没有正确排列,这可能会导致 python 出现问题。

第二项是您没有LogonSql在主文件中导入。

您应该声明以下内容,假设您的LogonSql类存储在一个名为的文件中logonsql.py,并且它与引用LogonSql该类的文件位于同一目录中:

from logonsql import LogonSql

之后,您可以致电您的班级并继续按照您的意愿使用它。请参阅屏幕截图作为对我的结构的参考。

在此处输入图像描述


推荐阅读