I have a modules.py file :
global dns_server_ip
def SetVnetGlobalParameters():
dns_server_ip = '192.168.3.120'
And I’m importing this file in say abc.py file
from modules import *
SetVnetGlobalParameters()
print(dns_server_ip)
But ‘dns_server_ip’ is still not accessible.
I want to set global parameters through Function only. Any help would be greatly appreciated! Thanks..
As per your question I understand you are the beginner to the python.
While importing the modules you have use just module name and don't need to include the extension or suffix(py) and in your code you miss the starting single quote .
Here is your modified code: it is modules.py
dns_server_ip = ''
def SetVnetGlobalParameters():
global dns_server_ip
dns_server_ip = '192.168.3.120′
Here is your abc.py
import modules
modules.SetVnetGlobalParameters()
print modules.dns_server_ip
Here through the global keyword we are telling the python interpreter to change or point out the global variable instead of local variable and always the variable would be either global
or local
If the variable is both (local and global) you will get python UnboundLocalError
exception and if you did not put that global keyword
global dns_server_ip
The dns_server_ip will be created as a new local variable . The keyword global
intended to with in the functions only
you can check global keyword,python modules
In modules.py
dns_server_ip = None
def SetVnetGlobalParameters():
global dns_server_ip
dns_server_ip = '192.168.3.120'
In abc.py
import modules
modules.SetVnetGlobalParameters()
print(modules.dns_server_ip)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With