简体   繁体   English

如何从不同的文件访问变量

[英]How to Access variable from different file

My first File "sk_read_write.py" is as follows:我的第一个文件“sk_read_write.py”如下:

  from spark_conn import *
    from Table_structure import *
    class read_write1:
        def sk_read_write1(self,schema,spark):
            df3 = spark.read.option("multiline", "true").option("mode", "PERMISSIVE").schema(schema).json(
                "C:\\Users\\komu0\\Desktop\\Read\\*.json")
            print(Spark_connect_1.connection())
            df3.write.format('jdbc').options( url= Spark_connect_1.connection+str(connection._port),
                                             driver='com.mysql.cj.jdbc.Driver',
                                             dbtable='sparktable',
                                             user=connection._username,
                                             password=Spark_connect_1.connection._pass).\
                                             mode('append').save()

My Other file is spark_conn.py:我的其他文件是 spark_conn.py:

from pyspark.sql.types import StructType,StructField, StringType, IntegerType,BooleanType,DoubleType
from aws_config import *
from Table_structure import*
class Spark_connect_1:
    dict1 = get_secret()
    def connection(self):
        dict1 = get_secret()
        _username = dict1['username']
        _pass = dict1['password']
        _host = dict1['host']
        _port = dict1['port']
        _dbname = dict1['dbname']
        spark = SparkSession.builder \
            .master("local[1]") \
            .appName("JSON_MYSQL") \
            .getOrCreate()

        return spark

I want to use the variable in " _port" into sk_read_write file.我想将“_port”中的变量用于 sk_read_write 文件。 I have tried to import spark_conn into sk_read_write file and use "Spark_connect_1.connection._port" (to get port name) but not working, please suggest how to proceed我试图将 spark_conn 导入 sk_read_write 文件并使用“Spark_connect_1.connection._port”(获取端口名称)但不工作,请建议如何继续

You can access the port name by using a class variable for _port您可以使用 _port 的_port变量来访问端口名称

Example例子

base_file.py base_file.py

class ABC:
    _port = "Some value"

    def sample(self):

        ABC._port = "another value"

        print("Value of port is {}".format(ABC._port))

test_file.py测试文件.py

from base_file import  ABC

#before changing value:

before = ABC()
before.sample()

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

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