Error while init new class on function start - python

Why does it says that there is an argument missing when in code there is not ?
if correct:
listOfCities = rmg.genRandomListOfPoints(self.numOfPointsVal,800,400)
for algoType, isChoosen in self.checkBoxDict.items():
if isChoosen.get():
print(algoType)
p = mp.Process(target = self.run(listOfCities, self.numOfPointsVal, algoType))
p.start()
# close this windows, it is longer no necessary
self.destroy()
#-------------------------------------------------------------------------------------
def run(self, listOfCities, numOfPointsVal, algoType):
""" Starts other window from new process"""
t = InitFrame.__init__(listOfCities, numOfPointsVal , algoType)
** Consol output **
In the output it says that 1 is missing but that is not true.
It is not IDE depending
pmx
Exception in Tkinter callback
Traceback (most recent call last):
File "C:\Users\CrazyUrusai\AppData\Local\Programs\Python\Python36\lib\tkinter\__init__.py", line 1699, in __call__
return self.func(*args)
File "C:\Users\CrazyUrusai\git\WarsawSchoolOfAI\GeneticsAlgorithms\StartFrame.py", line 70, in <lambda>
startButton = tk.Button(text = "Start", bd = 3, bg = "#20aa20", command = lambda:self.start())
File "C:\Users\CrazyUrusai\git\WarsawSchoolOfAI\GeneticsAlgorithms\StartFrame.py", line 97, in start
p = mp.Process(target = self.run(listOfCities, algoType))
File "C:\Users\CrazyUrusai\git\WarsawSchoolOfAI\GeneticsAlgorithms\StartFrame.py", line 104, in run
t = InitFrame.__init__(listOfCities, self.numOfPointsVal, algoType)
TypeError: __init__() missing 1 required positional argument: 'algoType'

To create an object, you should not do that:
t = InitFrame.__init__(listOfCities, self.numOfPointsVal, algoType)
but that:
t = InitFrame(listOfCities, self.numOfPointsVal, algoType)
(An error is raised because when a method is called with the class name: InitFrame.method(), nothing is passed to the self argument)

Related

Calling a python script within another python script with args

Current Implementation which needs optimization
import subprocess
childprocess = subprocess.Popen(
['python',
'/full_path_to_directory/called_script.py',
'arg1',
'arg2'],
stdout=subprocess.PIPE,
stderr=subprocess.PIPE)
returnVal = childprocess.communicate()[0]
print(retVal)
Is this a correct way to call another script(called_script.py) within the current working directory?
Is there a better way to call the other script? I used import script but it gives me below error
called_script.py
def func(arg1, arg2, arg3):
#doSomething
#sys.out.write(returnVal)
if __name__ == "__main__":
func(arg1, arg2, arg3)
Implementation 2 (throws exception and errored out)
caller_script.py
Both of them are under the same path (i.e. /home/bin)
import called_script
returnVal = called_script.func(arg1,arg2,arg3)
print(returnVal)
Output:
nullNone
Traceback (most recent call last):
File "/path_to_caller/caller_script.py", line 89, in <module>
l.simple_bind_s(binddn, pw)
File "/usr/lib64/python2.6/site-packages/ldap/ldapobject.py", line 206, in simple_bind_s
msgid = self.simple_bind(who,cred,serverctrls,clientctrls)
File "/usr/lib64/python2.6/site-packages/ldap/ldapobject.py", line 200, in simple_bind
return self._ldap_call(self._l.simple_bind,who,cred,EncodeControlTuples(serverctrls),EncodeControlTuples(clientctrls))
File "/usr/lib64/python2.6/site-packages/ldap/ldapobject.py", line 96, in _ldap_call
result = func(*args,**kwargs)
TypeError: argument 2 must be string or read-only buffer, not None
Another alternative I used and gave me an error is
Implementation 3(throws exception and errors out)
caller_script.py
import ldap
returnVal = subprocess.call(['python','called_script.py','arg1','arg2'])
print(returnVal)
l = ldap.initialize(cp.get('some_config_ref','some_url'))
try:
l.protocol_version = ldap.VERSION3
l.simple_bind_s(binddn, returnVal)
except ldap.INVALID_CREDENTIALS:
sys.stderr.write("Your username or password is incorrect.")
sys.exit(1)
except ldap.LDAPError, e:
if type(e.message) == dict and e.message.has_key('xyz'):
sys.stderr.write(e.message['xyz'])
else:
sys.stderr.write(e)
sys.exit(1)
Output:
returnVal0Traceback (most recent call last):
File "./path_to_script/caller_script.py", line 88, in <module>
l.simple_bind_s(binddn, pw)
File "/usr/lib64/python2.6/site-packages/ldap/ldapobject.py", line 206, in simple_bind_s
msgid = self.simple_bind(who,cred,serverctrls,clientctrls)
File "/usr/lib64/python2.6/site-packages/ldap/ldapobject.py", line 200, in simple_bind
return self._ldap_call(self._l.simple_bind,who,cred,EncodeControlTuples(serverctrls),EncodeControlTuples(clientctrls))
File "/usr/lib64/python2.6/site-packages/ldap/ldapobject.py", line 96, in _ldap_call
result = func(*args,**kwargs)
TypeError: argument 2 must be string or read-only buffer, not int
Here is an example where you are calling a function from another file, you pass one value, a list, which can have an arbitrary amount of numbers, and you get the sum. Make sure they are in the same directory or you will need the path. The function in your example "script.py" does not allow you to pass a value.
called_script.py
def add_many(list_add):
the_sum = sum(list_add)
return the_sum
caller_script.py
import called_script
a_list = [1, 2, 3, 4]
the_sum = called_script.add_many(a_list)
print(the_sum)

TypeError: argument of type 'method' is not iterable (Tensorforce DQN Tutorial)

I am trying to do a tensorforce tutorial with a DQN algorithm, but I am running into some errors. It seems that tensorforce has been updated since this tutorial was written, so I am trying to figure things out on my own with the documentation. Anywho, here is my code.
import logging
from tensorforce.environments.openai_gym import OpenAIGym
from tensorforce.agents import DQNAgent
from tensorforce.execution import Runner
# def main():
gym_id = 'CartPole-v0'
max_episodes = 10000
max_timesteps = 1000
total_memory = 100
env = OpenAIGym(gym_id)
network_spec = [
dict(type='dense', size=32, activation='tanh'),
dict(type='dense', size=32, activation='tanh')
]
agent = DQNAgent(
# states_spec=env.states,
# actions_spec=env.actions,
states=env.states,
actions=env.actions,
# network_spec=network_spec,
batch_size=64,
memory=total_memory <-- Here is where my error is coming from.
)
runner = Runner(agent, env)
report_episodes = 10
def episode_finished(r):
if r.episode % report_episodes == 0:
logging.info("Finished episode {ep} after {ts} timesteps".format(ep=r.episode, ts=r.timestep))
logging.info("Episode reward: {}".format(r.episode_rewards[-1]))
logging.info("Average of last 100 rewards: {}".format(sum(r.episode_rewards[-100:]) / 100))
return True
print("Starting {agent} for Environment '{env}'".format(agent=agent, env=env))
runner.run(max_episodes, max_timesteps, episode_finished=episode_finished)
runner.close()
print("Learning finished. Total episodes: {ep}".format(ep=runner.episode))
# if __name__ == '__main__':
# main
With the error originating from
memory=total_memory
The documentation found here says that memory is required and that it must be an int>0, so I am confused. Any help would be sweet.
EDIT
Here is the traceback code.
Traceback (most recent call last):
File "test3.py", line 19, in <module>
agent = DQNAgent(
File "/home/dskinner/.local/lib/python3.8/site-packages/tensorforce/agents/dqn.py", line 217, in __init__
super().__init__(
File "/home/dskinner/.local/lib/python3.8/site-packages/tensorforce/agents/tensorforce.py", line 441, in __init__
super().__init__(
File "/home/dskinner/.local/lib/python3.8/site-packages/tensorforce/agents/agent.py", line 243, in __init__
super().__init__(
File "/home/dskinner/.local/lib/python3.8/site-packages/tensorforce/agents/recorder.py", line 50, in __init__
if 'type' in states or 'shape' in states:
TypeError: argument of type 'method' is not iterable

How to recover the return value of a function passed to multiprocessing.Process?

I have looked at this question to get started and it works just fine How can I recover the return value of a function passed to multiprocessing.Process?
But in my case I would like to write a small tool, that would connect to many computers and gather some statistics, each stat would be gathered within a Process to make it snappy. But as soon as I try to wrap up the multiprocessing command in a class for a machine then it fails.
Here is my code
import multiprocessing
import pprint
def run_task(command):
p = subprocess.Popen(command, stdout = subprocess.PIPE, universal_newlines = True, shell = False)
result = p.communicate()[0]
return result
MACHINE_NAME = "cptr_name"
A_STAT = "some_stats_A"
B_STAT = "some_stats_B"
class MachineStatsGatherer():
def __init__(self, machineName):
self.machineName = machineName
manager = multiprocessing.Manager()
self.localStats = manager.dict() # creating a shared ressource for the sub processes to use
self.localStats[MACHINE_NAME] = machineName
def gatherStats(self):
self.runInParallel(
self.GatherSomeStatsA,
self.GatherSomeStatsB,
)
self.printStats()
def printStats(self):
pprint.pprint(self.localStats)
def runInParallel(self, *fns):
processes = []
for fn in fns:
process = multiprocessing.Process(target=fn, args=(self.localStats))
processes.append(process)
process.start()
for process in processes:
process.join()
def GatherSomeStatsA(self, returnStats):
# do some remote command, simplified here for the sake of debugging
result = "Windows"
returnStats[A_STAT] = result.find("Windows") != -1
def GatherSomeStatsB(self, returnStats):
# do some remote command, simplified here for the sake of debugging
result = "Windows"
returnStats[B_STAT] = result.find("Windows") != -1
def main():
machine = MachineStatsGatherer("SOMEMACHINENAME")
machine.gatherStats()
return
if __name__ == '__main__':
main()
And here is the error message
Traceback (most recent call last):
File "C:\Users\mesirard\AppData\Local\Programs\Python\Python37\lib\multiprocessing\process.py", line 297, in _bootstrap
self.run()
File "C:\Users\mesirard\AppData\Local\Programs\Python\Python37\lib\multiprocessing\process.py", line 99, in run
self._target(*self._args, **self._kwargs)
File "d:\workdir\trunks6\Tools\VTKAppTester\Utils\NXMachineMonitorShared.py", line 45, in GatherSomeStatsA
returnStats[A_STAT] = result.find("Windows") != -1
TypeError: 'str' object does not support item assignment
Process Process-3:
Traceback (most recent call last):
File "C:\Users\mesirard\AppData\Local\Programs\Python\Python37\lib\multiprocessing\process.py", line 297, in _bootstrap
self.run()
File "C:\Users\mesirard\AppData\Local\Programs\Python\Python37\lib\multiprocessing\process.py", line 99, in run
self._target(*self._args, **self._kwargs)
File "d:\workdir\trunks6\Tools\VTKAppTester\Utils\NXMachineMonitorShared.py", line 50, in GatherSomeStatsB
returnStats[B_STAT] = result.find("Windows") != -1
TypeError: 'str' object does not support item assignment
The issue is coming from this line
process = multiprocessing.Process(target=fn, args=(self.localStats))
it should have a extra comma at the end of args like so
process = multiprocessing.Process(target=fn, args=(self.localStats,))

APScheduler ValueError: The target callable does not accept the following keyword arguments:

I am running into an error calling add_job with kwargs for a function:
I created a function to create scheduled jobs:
def initial_data_pull():
q.enqueue(initial_pull, timout='3h')
def initial_data_load():
dates_list = date_between_list(start=date(2010, 1, 1), stop=date.today())
naics = ['541611', '541618', '541613',
'541511', '541512', '541513',
'541519', '518210', '541612']
fundings = ['3600', '97DH', '7504', '7505',
'7522', '7523', '7524', '7526',
'7527', '7528', '7529', '7530',
'7570']
for date_item in dates_list:
for fund in fundings:
for naic in naics:
sched.add_job(initial_data_pull,
kwargs={'naics_code': naic,
'funding_agency_id': fund,
'date_signed': date_item})
The function initial_pull looks like:
def initial_pull(naics_code=None, funding_agency_id=None, date_signed=None):
print('Gathering Contracts...')
df = fpds_generic(naics_code=naics_code,
funding_agency_id=funding_agency_id,
date_signed=date_signed)
# Code to Process and load data
The function fpds_generic is a function that goes to fpds and gather's data. I am getting the following error when I run the inital_data_load function.
Traceback (most recent call last):
File "clock.py", line 55, in <module>
initial_data_load()
File "clock.py", line 52, in initial_data_load
sched.add_job(initil_data_pull, kwargs=kw)
File "/home/spitfiredd/anaconda3/envs/g2x_flask/lib/python3.6/site-packages/apscheduler/schedulers/base.py", line 425, in add_job
job = Job(self, **job_kwargs)
File "/home/spitfiredd/anaconda3/envs/g2x_flask/lib/python3.6/site-packages/apscheduler/job.py", line 44, in __init__
self._modify(id=id or uuid4().hex, **kwargs)
File "/home/spitfiredd/anaconda3/envs/g2x_flask/lib/python3.6/site-packages/apscheduler/job.py", line 175, in _modify
check_callable_args(func, args, kwargs)
File "/home/spitfiredd/anaconda3/envs/g2x_flask/lib/python3.6/site-packages/apscheduler/util.py", line 385, in check_callable_args
', '.join(unmatched_kwargs))
ValueError: The target callable does not accept the following keyword arguments: naics_code, funding_agency_id, date_signed
Why is it saying that the function does not accept those keyword args when it does, and how do I fix this?

Python Tkinter : AttributeError: Button instance has no __call__ method

I don't know why this is giving me an attribute error. I want my blah() function to shuffle the cards. I'm calling the builtin function shuffle() from random.
Error:
Exception in Tkinter callback
Traceback (most recent call last):
File "/usr/lib/python2.7/lib-tk/Tkinter.py", line 1489, in __call__
return self.func(*args)
File "gui1.py", line 105, in blah
shuffle(cards)
AttributeError: Button instance has no __call__ method
Here's the code snippet:
def blah():
global card_count
global path
shuffle(cards)
card_count = 0
path = generate_paths(cards)
print "Cards Shuffled"
shuffle = Button(frame_buttons, text = "SHUFFLE",height = 2, width = 10,command =blah)
shuffle.grid(row = 2 , padx = 40, pady = 40)
shuffle is the name of the function in random. However, it's also the name of the Button. Change the Button's name to something like shuffle_button and you should be fine.

Categories