skip to Main Content

in python I have this set of variable

variable.py

#--------------Project 1--------------#
ip_server = '10.10.55.98'
username = 'user_1'
distro = 'debian'

#--------------Project 2--------------#
ip_server = '10.10.55.96'
username = 'user_2'
distro = 'opensuse'

#--------------Project 3--------------#
ip_server = '10.10.55.95'
username = 'user_3'
distro = 'ubuntu'

In the script main.py I just want to import variable of Project 2, how to this?

main.py

from variable import *

ho_to_import_variable_of_project2?


thanks to all for answers anche time to dedicate my question

2

Answers


  1. Create a list and dictionary for each project like below:

    variable.py
    
    project1 = [{'ip_server' :'10.10.55.98', 'username':'user_1', 'distro' : 'debian'}]
    project2 = [{'ip_server' :'10.10.55.95', 'username':'user_2', 'distro' : 'opensuse'}]
    project3 = [{'ip_server' :'10.10.55.96', 'username':'user_3', 'distro' : 'ubuntu'}]
    

    And in main.py

    from variable import project1
    
    Login or Signup to reply.
  2. Your assumption that using comments to "separate" the variables to logical groups means anything to the interpreter is wrong. All you are really doing is overwriting the same variables.

    Also, avoid using import *.

    Instead, I’d use a dictionary:

    data = {
        'Project 1': {
            'ip_server': '10.10.55.98',
            'username': 'user_1',
            'distro': 'debian'
        },
        'Project 2': {
            'ip_server': '10.10.55.96',
            'username': 'user_2',
            'distro': 'opensuse'
        },
        'Project 3': {
            'ip_server': '10.10.55.95',
            'username': 'user_3',
            'distro': 'ubuntu'
        }
    }
    

    then use it:

    from variable import data
    
    print(data['Project 1']['ip_server'])
    

    will output

    10.10.55.98
    

    At this point you might as well use an external JSON file as a config file but that is behind the scope of this question/answer.

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search