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.
Related
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
Can't instantiate objects using python interpreter, please help.
So inside of my python file expresser.py I have something like
class Expresser:
def __init__(self):
pass
...
Now when I type in the terminal
python
and then
>>> import expresser
>>> test_object = Expresser()
I get:
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
NameError: name 'Expresser' is not defined
I'm using PyCharm
when I type where python I get three diff locations so I suspect that but don't know how to rectify
I guess you meant:
from expresser import Expresser
Or:
from expresser import *
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)
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.
The documentation is really vague about subclassing the CommandLineApp, only mentioning one example:
class YourApp(cli.app.CommandLineApp):
def main(self):
do_stuff()
So with the information I've found I've pieced together this code:
#!/usr/bin/env python
import os
import sys
from cli.app import CommandLineApp
# Append the parent folder to the python path
sys.path.append(os.path.join(os.path.dirname(__file__), '../'))
import tabulardata
from addrtools import extract_address
class SplitAddressApp(CommandLineApp):
def main(self):
"""
Split an address from one column to separate columns.
"""
table = tabulardata.from_file(self.params.file)
def for_each_row(i, item):
addr = extract_address(item['Address'])
print '%-3d %-75s %s' % (i, item['Address'], repr(addr))
table.each(for_each_row)
def setup(self):
self.add_param('file', metavar='FILE', help='The data file.')
self.add_param(
'cols', metavar='ADDRESS_COLUMN', nargs='+',
help='The name of the address column. If multiple names are ' + \
'passed, each column will be checked for an address in order'
)
if __name__ == '__main__':
SplitAddressApp().run()
Which seems correct to me. The documentation gives no examples on how to handle the setup method or running the application when using subclassing. I get the error:
Traceback (most recent call last):
File "bin/split_address_column", line 36, in
SplitAddressApp().run()
File "/Users/tomas/.pythonbrew/venvs/Python-2.7.3/address_cleaner/lib/python2.7/site-packages/cli/app.py", line 440, in __init__
Application.__init__(self, main, **kwargs)
File "/Users/tomas/.pythonbrew/venvs/Python-2.7.3/address_cleaner/lib/python2.7/site-packages/cli/app.py", line 129, in __init__
self.setup()
File "bin/split_address_column", line 28, in setup
self.add_param('file', metavar='FILE', help='The data file.')
File "/Users/tomas/.pythonbrew/venvs/Python-2.7.3/address_cleaner/lib/python2.7/site-packages/cli/app.py", line 385, in add_param
action = self.argparser.add_argument(*args, **kwargs)
AttributeError: 'SplitAddressApp' object has no attribute 'argparser'
So presumably I'm doing something wrong, but what?
I figured it out. Reading the source of pyCLI it turns out that the setup function is quite important for the functionality of the whole library, while I thought it was just a function where I could put my setup code. argparser is created in cli.app.CommandLineApp.setup which means I at least have to call
cli.app.CommandLineApp.setup(self)
inside the setup function for it to even work. And now the code works perfectly!