I am writing many small python scripts and keeping in one directory and i am calling them in different scripts
Below is the script and it is calling function that has saved in another director acc_repo:
from acc_repo import col
import logging
import getpass
col.col()
dc = raw_input(OKGREEN + "Choose DataCenter:" + ENDC)
File "ucs_qa.py", line 21, in <module>
dc = raw_input(OKGREEN + "Choose DataCenter:" + ENDC)
NameError: name 'OKGREEN' is not defined
function that is saved in acc_repo directory
def col ():
global HEADER
global OKBLUE
global OKGREEN
global WARNING
global FAIL
global ENDC
global BOLD
global UNDERLINE
HEADER = '\033[95m'
OKBLUE = '\033[94m'
OKGREEN = '\033[92m'
WARNING = '\033[93m'
FAIL = '\033[91m'
ENDC = '\033[0m'
BOLD = '\033[1m'
UNDERLINE = '\033[4m'
How do i fix the error? Is i am in right track in terms handling many small python scripts. Please advice and help to fix the issue
Try
col.OKGREEN
Just like functions, variables in different files need to know where they reside in. This allows developers to create same named variables without bothering what library they are importing.
Your function col.col() declares global variables, but they are still in the scope of the module in which they are declared. So after calling col.col()
, you can access the declared variables by qualifying the name with the col
module. For example, you can access OKGREEN
with col.OKGREEN
(updated the answer) Try this:
from acc_repo import col
import logging
import getpass
col.col()
# import the OKGREEN.. etc after col()
from acc_repo.col import *
dc = raw_input(OKGREEN + "Choose DataCenter:" + ENDC)
The global variables are intialized after col() is called.
But this is more like a fast workaround to make your code work. I guess you tried to make the global variables "global" in main.py by calling col()
, but they are actually only global in the scope of col.py. Therefore, the from acc_repo.col import *
is still necessary after col()
is called.
To achieve what you want, modify col.py to (as @Maurice's answer):
HEADER = '\033[95m'
OKBLUE = '\033[94m'
OKGREEN = '\033[92m'
WARNING = '\033[93m'
FAIL = '\033[91m'
ENDC = '\033[0m'
BOLD = '\033[1m'
UNDERLINE = '\033[4m'
then remove the line col.col()
, and keep the other as they are.
Dont use global variables at all !
acc_repo.py:
HEADER = '\033[95m'
OKBLUE = '\033[94m'
OKGREEN = '\033[92m'
WARNING = '\033[93m'
FAIL = '\033[91m'
ENDC = '\033[0m'
BOLD = '\033[1m'
UNDERLINE = '\033[4m'
main.py:
from acc_repo import *
import logging
import getpass
dc = raw_input(OKGREEN + "Choose DataCenter:" + ENDC)
print(dc)
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.