I need some help because I keep getting this erros:
Traceback (most recent call last):
File "/home/kostas_ubuntu/HemTools/bin/chromHMM.py", line 173, in <module>
main()
File "/home/kostas_ubuntu/HemTools/bin/chromHMM.py", line 100, in main
args = my_args()
File "/home/kostas_ubuntu/HemTools/bin/chromHMM.py", line 43, in my_args
input.add_argument('-bin',"--chromHMM_jar", help="chromHMM bin location",default=myPars['chromHMM_jar'])
NameError: global name 'myPars' is not defined
I run the script and get this error although in the script I import the utils.py module that sets the myPars variable. The below code snippet comes from the utils.py module.
p_dir = os.path.dirname(os.path.realpath(__file__)) + "/"
username = getpass.getuser()
myData = parse_config(p_dir+"../config/data.config")
myPars = parse_config(p_dir+"../config/parameters.config")
More information of the scripts you can find on the github links below:
utils.py -> https://github.com/YichaoOU/HemTools/blob/master/utils/utils.py
chromHMM.py ->https://github.com/YichaoOU/HemTools/blob/master/bin/chromHMM.py
Thanks in advance!
In Python 3 you should declare on every new scope the global variables it uses. In your case it'd be like the following:
def my_args():
global myPars, myData
# ... The remaining code
# ...
def main():
global myData, myPipelines
# ... The remaining code
Related
I am trying to import some variables from a different python file resides in the same directory from a another python file.
I have two files in the same directory as below:
constantvariables.py
test.py
This is how constantvariables.py looks like
class CONST(object):
FOO = 1234
NAMESPACE = "default"
DEPLOYMENT_NAME = "deployment-test"
DOCKER_IMAGE_NAME = "banukajananathjayarathna/bitesizetroubleshooter:v1"
SERVICE_CLUSTER = "deployment-test-clusterip"
SERVICE_NODEPORT = "deployment-test-nodeport"
INGRESS_NAME = "deployment-test-ingress"
def __setattr__(self, *_):
pass
CONST = CONST()
and this is how my test.py looks like:
import os
from . import constantvariables
print(constantsvariables.NAMESPACE)
But I get this error:
Traceback (most recent call last):
File "test.py", line 7, in
from . import constantsvariables
ImportError: cannot import name 'constantsvariables'
can someone please help me?
Python version I am using python 2.7.5
Make constant file like that constant.py and put inside config folder for proper management.
FOO = 1234
NAMESPACE = "default"
DEPLOYMENT_NAME = "deployment-test"
DOCKER_IMAGE_NAME = "banukajananathjayarathna/bitesizetroubleshooter:v1"
SERVICE_CLUSTER = "deployment-test-clusterip"
SERVICE_NODEPORT = "deployment-test-nodeport"
INGRESS_NAME = "deployment-test-ingress"
Inside your base directory create main.py file and call the constant inside that.
import os
from config.constants import NAMESPACE, FOO
print(NAMESPACE)
If you want to keep your constant file as it is, you can write this:
import os
from constantvariables import CONST
print(CONST.NAMESPACE)
config.py
import json
import os
myfolder = os.path.dirname(os.path.realpath(__file__))
configfile = os.path.join(myfolder, '../appconfig.json')
appconfig = None
def get_config():
if myfolder is None:
return myfolder
if appconfig is not None:
return appconfig
else:
#load the config
try:
with open(configfile) as json_data:
c = json.load(json_data)
appconfig = c
return c
except Exception, e:
raise Exception("Cannot load config file %s : %s"%(configfile, `e`))
Now import it and use it:
tmp.py
import config
config.get_config()
python tmp.py
Traceback (most recent call last):
File "tmp.py", line 2, in <module>
config.get_config()
File "D:\projects\flask_ndc\lib\config.py", line 12, in get_config
if appconfig is not None:
UnboundLocalError: local variable 'appconfig' referenced before assignment
Comment out line 18 in config.py
#appconfig = c
Now the code works - (but of course without saving the content in the global variable)
Can somebody explain why the python interpreter is not able to see that the assignment of appconfig in line 18 refers to the module-global variable appconfig, declared in line 7 ????
You problem is this line:
appconfig = c
It means define a new name in locals of function get_config.
So when Interpreter run this line:
if appconfig is not None:
It treat name "appconfig" as a local variable, but it is not defined in former local codes, so the exception cames out.
If you don't assign any thing to appconfig in function get_config, the Interpreter considers appconfig as a enclosing name, and use appconfig in module-level.
If you want to assign value to appconfig in function, just use "global" to declare, add
global appconfig
before the very first line appconfig appears.
Hope I can help you. Feel free to comment any other questions about this post.
I have two files,
main.py
options.py
main.py is my main program. I import options.py via:
from options import Options
whereas "options" is a class I defined in options.py
Options has a custom init method:
def __int__(self, afc="red", awc="orange", asc="gray", apn=1738):
If I try to make an object from within main.py like so:
options = Options("red","green","blue",1738)
Python tells me that there are unexpected arguments. How can I instantiate the object with my custom init method?
here is the respective code of my options.py file:
class Options:
anyBarFailureColor = ""
anyBarWarningColor = ""
anyBarScrubInProgressColor = ""
anyBarPortNumber = 0
def __int__(self, afc="red", awc="orange", asc="gray", apn=1738):
self.anyBarFailureColor = afc
self.anyBarWarningColor = awc
self.anyBarScrubInProgressColor = asc
self.anyBarPortNumber = apn
here is the Python error:
Traceback (most recent call last):
File "/pathToFile/Python/project/main", line 58, in <module>
start()
File "/pathToFile/Python/project/main.py", line 55, in start
options,listOfPools=mapArgs(args)
File "/pathToFile/Python/project/main.py", line 39, in mapArgs
options = Options(anyBarFailureColor,anyBarWarningColor,anyBarScrubInProgressColor,anyBarPortNumber)
TypeError: object() takes no parameters
One should neither type int nor index and wonder why it isn't working. Sigh. Typo, never was a init to begin with. Now everything works.
I am trying to run a cmd script which calls a setenv.py file. This file has a function which says,
import build_cfg
tool_versions = get_tool_versions()
env_var_list = get_env_var()
which I believe is importing the build_cfg module.
build_cfg in turn has get_tool_versions and get_env_vars functions defined.
Anyway, when I run my script I get an error :
File "setenv.py", line 172, in <module>
tool_versions = get_tool_versions ()
NameError: name 'get_tool_versions' is not defined
I am relatively new to python. Could you please tell me what I am doing wrong?
The error message says it all: The function get_tool_versions does not exist in the global namespace.
To solve this problem you have to find out where get_tool_versions is defined and import it from there. If it is defined in build_cfg you can do it like this:
import build_cfg
tool_versions = build_cfg.get_tool_versions()
...
or
from build_cfg import get_tool_versions
tool_versions = get_tool_versions()
...
I am new to unnitest module. I have a file that has unittest in it. The file is something like ...
File1.py
class ABC (unittest.TestCase):
def setUp(self):
# Do some work here
def test_123(self, a,b,c):
# Do some work here
if __name__ == "__main__":
unittest.main()
*Now I am calling this file from another file by passing values to the function "test_123".* But python displays the following error. Could anybody please help!
Traceback (most recent call last):
File "caller_file.py", line 20, in <module>
r = file1.ABC()
File "/usr/lib/python2.7/unittest/case.py", line 191, in __init__
(self.__class__, methodName))
ValueError: no such test method in <class 'file1.ABC'>: runTest
You can run file1.ABC test case like this:
import unittest
import file1
suite = unittest.TestLoader().loadTestsFromTestCase(file1.ABC)
unittest.TextTestRunner(verbosity=2).run(suite)
Also you need to add the self argument to the setUp and test_123 methods and self should be the sole argument.
I run into similar problems with my unittests because missing entries in search path for modules.
I solved it by creating
my_env = os.environ.copy()
if not 'PYTHONPATH' in my_env:
my_env['PYTHONPATH'] = ''
my_env['PYTHONPATH'] += ';' + ';'.join(
[os.path.abspath('.'),
os.path.abspath('..'),
os.path.abspath('..\\..')])
and then the call of the file
_ = subprocess.check_output(filepath, shell=True, env=my_env)
I just added the current path environment because the calling-file is in the same directories. Maybe you have to adjust that.