首页 > 解决方案 > 将一个文件的 fun var 值访问到另一个 fun 中还是在另一个 python 文件的 fun 之外?

问题描述

我有三个 python 文件问题是我正在尝试访问 test.py 文件中 sample.py 中定义的变量(“用户名”),因此我可以使用该变量或任何其他变量的值并将其传递给函数或如果我可以直接访问 test.py 的函数(test_target)中的任何变量值

示例.py

from configparser import ConfigParser

parser = ConfigParser()
parser.read('config.ini')


def GetEnviornment():
    env = input("Enter Environment name : ") or 'Dev Site'
    return env

def GetConnectionString():
    env = GetEnviornment()
    username = parser.get(env, 'username')
    password = parser.get(env, 'password')
    dbname = parser.get(env, 'dbname')

    return "%s/%s@%s" % (username, password, dbname)

连接.py

import cx_Oracle
import sample

class Connection(cx_Oracle.Connection):

    def __init__(self):
        connectString = test.GetConnectionString()
        print("CONNECT to database")
        return super(Connection, self).__init__(connectString)

    def cursor(self):
        return Cursor(self)


class Cursor(cx_Oracle.Cursor):

    def execute(self, statement):
        print("EXECUTE", statement)
        return super(Cursor, self).execute(statement)

    def fetchall(self):
        print("FETCH ALL")
        return super(Cursor, self).fetchall()

测试.py

from connection import *    
from sample import *

def test_target(user_suffix,hash_value):
    connection = Connection()
    cursor = connection.cursor()
    cursor.execute("select * from dba_users u where u.USERNAME like '{}'".format(username))
    rows = cursor.fetchall()
    for row in rows:
        print(row)
    cursor.close()
    connection.close()

user_suffix="Hello"
hash_value="12345"
test_target(user_suffix,hash_value)

标签: oraclepycharmwindows-10python-3.8

解决方案


我在 test.py 中进行了更改。您可以从连接中提取任何您想要的条目,例如用户名、dsn。Connection 类中还有其他功能

from connection import *    
from sample import *

def test_target(user_suffix,hash_value):
    connection = Connection()
    cursor = connection.cursor()
    username = connection.username
    cursor.execute("select * from dba_users u where u.USERNAME like '{}'".format(username))
    rows = cursor.fetchall()
    for row in rows:
        print(row)
    cursor.close()
    connection.close()

user_suffix="Hello"
hash_value="12345"
test_target(user_suffix,hash_value)

推荐阅读