-1

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

Nimantha
  • 6,405
  • 6
  • 28
  • 69
Bender
  • 49
  • 6
  • Does `from variable import *` not work for you? By the way, you are just redefining `ip_server`, `username`, and `distro` 3 times so at the end you will only have 3 variables, not 9. – Axe319 Jan 27 '22 at 11:14
  • 1
    You do not have separate variables for projects 1, 2, 3 – you overwrite the same variables each time, and at the end you only have the values for project 3. – mkrieger1 Jan 27 '22 at 11:16
  • Is your question how to **import** something (because you already seem to know that) or how to create **different variables** for each project? – mkrieger1 Jan 27 '22 at 11:17
  • Potential duplicate https://stackoverflow.com/questions/14573021/python-using-variables-from-another-file – Josip Juros Jan 27 '22 at 11:17

2 Answers2

4

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.

DeepSpace
  • 78,697
  • 11
  • 109
  • 154
0

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
Devang Sanghani
  • 731
  • 5
  • 14