Run process when variable is called - python

I wanted to run code placed inside of thing.process upon when I hit the command.processCommand object (when i'm looping through all of the commands placed inside of defined[]), is there a way I can achieve this? This aforementioned loop will be executed as is such in myproject.py
command.py
class Command:
global defined
defined = []
def __init__(self, name):
self.name = name
self.description = "This command lacks a description"
self.args = ""
self.process = None
defined.append(self)
eightball.py
def processCommand():
print('hello')
thing = commands.Command('8ball')
thing.description = "Gives you a response from the mighty 8ball."
thing.process = processCommand
myproject.py
# Cogs
import cogs.commands as commands
import cogs.eightball
import cogs.helloworld
def processCommands(message):
if(message.content[:2] == "b#"):
args = message.content.split(' ')
args[0] = args[0][2:]
for command in defined:
if args[0] == command.name:
command.args = args
command.processCommand

for x in defined:
if x.process: # to skip `self.process = None`
x.process()
EDIT: you need process() instead of processCommand
for command in defined:
if args[0] == command.name:
command.args = args
command.process()

Related

How to pass a variable from a function to a class?

How can I print path outside function:
class FirstClas:
path = ''
def num(self):
path = "C:\\Users\\JOHN\\Desktop\\test.txt"
return path
print(path)
This method don't print anything.
This result:
C:\Python\python.exe C:/Users/JOHN/Desktop/test/tt.py
Process finished with exit code 0
You need to create an instance from the class that you created.
I would suggest doing this:
test = FirstClas()
print(test.num())
Hope this helps
Your method never gets called, and the class variable path is pointless here. Do:
class FirstClas:
def num(self):
path = "C:\\Users\\JOHN\\Desktop\\test.txt"
return path
print(FirstClas().num()) # note that this is outside the class!
I don't think you quite understand the purpose of classes, but here's how to make what you have "work" (in the sense that there are no fatal errors):
File global_variable.py
def init_global_variable():
"""initialize variable"""
global GLOBALS_DICT
GLOBALS_DICT = {}
def set_variable(name, value):
"""set variable"""
try:
GLOBALS_DICT[name] = value
return True
except KeyError:
return False
def get_variable(name):
"""get variable"""
try:
return GLOBALS_DICT[name]
except KeyError:
return "Not Found"
init_global_variable() # ADDED.
File tt.py
import os
#import lib.global_variable as glv
import global_variable as glv # Since I don't have your whole package.
class FirstClas:
def num(self):
path = "C:\\Users\\JOHN\\Desktop\\test.txt"
return path
def imag(self):
icon_file = os.path.join(
glv.get_variable("APP_PATH"),
glv.get_variable("DATA_DIR"),
"paths",
"PathExcel",
)
return icon_file
class Second:
# Put statements in a method so they don't run when the class is defined.
def run(self):
test = FirstClas()
print('first: ' + test.num())
print('second: ' + test.imag())
second = Second()
second.run()
Output:
first: C:\Users\JOHN\Desktop\test.txt
second: Not Found\Not Found\paths\PathExcel
the path does not changed(path = ' ') because you don't run the function num

Variable is undefined error. Calling a variable outside of condition in python

I'm parsing xml data and when i print the variable inside the condition but when i call that same variable later is not defined. Why does this happen
Here the variable "LaunchPath works fine:
import xml.sax
class PathHandler( xml.sax.ContentHandler ):
def __init__(self):
self.CurrentData = ""
# Call when an element starts
def startElement(self, tag, attributes):
self.CurrentData = tag
if tag == "application":
LaunchApp = attributes["android:name"].replace(".", "/")
LaunchPath = LaunchApp + ".smali"
print LaunchPath
if ( __name__ == "__main__"):
# create an XMLReader
parser = xml.sax.make_parser()
# turn off namepsaces
parser.setFeature(xml.sax.handler.feature_namespaces, 0)
# override the default ContextHandler
Handler = PathHandler()
parser.setContentHandler( Handler )
parser.parse("AndroidManifest.xml")
But when i attempt to print "LaunchPath" at the bottom like this it doesn work:
import xml.sax
class PathHandler( xml.sax.ContentHandler ):
def __init__(self):
self.CurrentData = ""
# Call when an element starts
def startElement(self, tag, attributes):
self.CurrentData = tag
if tag == "application":
LaunchApp = attributes["android:name"].replace(".", "/")
LaunchPath = LaunchApp + ".smali"
if ( __name__ == "__main__"):
# create an XMLReader
parser = xml.sax.make_parser()
# turn off namepsaces
parser.setFeature(xml.sax.handler.feature_namespaces, 0)
# override the default ContextHandler
Handler = PathHandler()
parser.setContentHandler( Handler )
parser.parse("AndroidManifest.xml")
print LaunchPath
This gives me an error that "LaunchPath" is undefined.
Why does this happen and how can i fix it.
This is because your variable LaunchPath is defined inside the scope of the function startElement, since you declared it there when the functions returns it also "erases" the variable.
You should read about python scopes
That is because LaunchPath is a local variable and you are trying to reference it out of its scope.

python error NameError: name 'ofclass' is not defined

I have an task to do to figure out what the code below does. it looks like it was constructed in python2 but I want to use python3. I have installed argparse which it requires and set up necessary file path but every time I run the program in command Line I get these issues.
Traceback (most recent call last):
File "C:\Users\Name\pythonScripts\Noddy.py", line 6, in <module>
class Noddy:
File "C:\Users\Name\pythonScripts\Noddy.py", line 63, in Noddy
if __name__ == '__main__': main()
File "C:\Users\Name\pythonScripts\Noddy.py", line 57, in main
ent = Noddy.make(fools)
NameError: name 'Noddy' is not defined
The code is below.
#! python3
class Noddy:
def __init__(self, x):
self.ant = None
self.dec = None
self.holder = x
#classmethod
def make(self, l):
ent = Noddy(l.pop(0))
for x in l:
ent.scrobble(x)
return ent
def scrobble(self, x):
if self.holder > x:
if self.ant is None:
self.ant = Noddy(x)
else:
self.ant.scrobble(x)
else:
if self.dec is None:
self.dec = Noddy(x)
else:
self.dec.scrobble(x)
def bubble(self):
if self.ant:
for x in self.ant.bubble():
yield x
yield self.holder
if self.dec:
for x in self.dec.bubble():
yield x
def bobble(self):
yield self.holder
if self.ant:
for x in self.ant.bobble():
yield x
if self.dec:
for x in self.dec.bobble():
yield x
def main():
import argparse
ap = argparse.ArgumentParser()
ap.add_argument("foo")
args = ap.parse_args()
foo = open(args.foo)
fools = [int(bar) for bar in foo]
ent = Noddy.make(fools)
print(list(ent.bubble()))
print
print(list(ent.bobble()))
if __name__ == '__main__': main()
Your def main() and if __name__=='__main__' have been written inside your class. The interpreter tries to execute them while it is defining the class, and can't, because the class Noddy doesn't exist until the class definition is finished.
Fix the indentation so that the main stuff lies outside your class.
class Noddy:
def __init__(self, x):
self.ant = None
self.dec = None
self.holder = x
# other methods INSIDE the class
# ...
# Notice the indentation — this function is OUTSIDE the class
def main():
# whatever main is supposed to do
# ...
if __name__=='__main__':
main()

Lazy parameter binding in Python

I tried to design a workflow using composite pattern, the sample codes looks like this:
class CommandInterface(object):
def __init__(self, name, template=None, tool=None, param : dict={},input=None, output=None ):
self.name = name
self.input = input
self.output = output
self.param = param
self.template = template
def before_invoke(self):
pass # check before invoke
def invoke(self):
pass
def after_invoke(self):
pass # check after invoke
class ShellCommand(CommandInterface):
def render(self):
cmd = self.template.format(input=self.input,
output=self.output,
param=self.param,
)
return cmd
def before_invoke(self):
pass
def invoke(self):
os.system(self.render())
class Workflow(CommandInterface):
def __init__(self, name):
self.name = name
self._input = []
self._output = []
self._commands = []
self._tool = []
def add(self, command : CommandInterface):
self._commands.append(command)
return self
def invoke(self):
for command in self._commands:
command.invoke()
And can be used like this:
workflow = Workflow()
raw_files = ["file1", "file2", "file3"]
for i in raw_files:
head_command = ShellCommand("head {input} {output}",
input = i,
output = i+"_head")
workflow.add(head_command)
merge_command = ShellCommand("cat {input} > {output}",
input=" ".join([i+"_head" for i in rawfiles]),
output="merged")
workflow.add(merge_command)
workflow.invoke()
However, sometimes a command's input might be another command's result, for example:
class PythonCommand(CommandInterface):
def invoke(self):
self._result = self.template(input=self.input, output=self.output, param=self.param)
def a_command(input, output, param):
take_long_time(input, output, param)
return {"a_result": "some result will be used in b_command"}
def b_command(input, output, param):
def need_the_result_of_a_command(input, output, param):
return param["a_result"]
need_the_result_of_a_command(input, output, param)
return "success"
a = PythonCommand(a_command, input_, output_, param_)
a.invoke()
b = PythonCommand(b_command, input_, output_, param= a._result)
b.invoke()
I can't use a workflow to composite these 2 command because b uses a's result as parameter, which is only visiable after a is invoked. However, a workflow manager like the codes before is still necessary in some situations. I think I need something like this:
workflow = Workflow()
a = PythonCommand(a_command, input_, output_, param_)
workflow.add(a)
b = PythonCommand(b_command, input_, output_, param= {"a_result": a.lazy()._result})
workflow.add(b)
workflow.invoke()
Does anyone have ideas about how to design a workflow with .lazy() implementation like this?

Python : Object is not avaialbe on different file

I have created a singlton Here is the class description.
allsms.py
from DB.models import ApiKey,ServiceProvider
from DB.messagenet import MessageNet
class SMSMgr( object ):
_instance = None
_allsp = []
def __init__(self):
pass
def __new__(cls, *args, **kwargs):
if not cls._instance :
cls._instance = super(SMSMgr, cls).__new__(
cls, *args, **kwargs)
return cls._instance
def loadsettings(self):
get_all_sp = ServiceProvider.objects.filter(status = False)
for obj in get_all_sp:
cla = obj.class_Name
a=globals()[str(obj.class_Name)](obj.userName,obj.password,obj.sendingurl)
self._allsp.append(a)
#print self._allsp
def reload(self):
self._allsp = []
get_all_sp = ServiceProvider.objects.filter(status = False)
for obj in get_all_sp:
cla = obj.class_Name
a=globals()[str(obj.class_Name)](obj.userName,obj.password,obj.sendingurl)
self._allsp.append(a)
def send(self):
print "+++++++++++++++++++== Global send "
if __name__ == "__main__":
b = SMSMgr()
b.loadsettings()
Now in test.py file of the same directory I am trying to use the singleton object which stored in the _allsp variable like.
from SMShandler.allsms import SMSMgr
b = SMSMgr()
#b.loadsettings()
print b._allsp
This is printing empty list. But when I am doing like this:
b = SMSMgr()
b.loadsettings()
print b._allsp
it is printing the list of objects .
My question is, if the above design is singlton then why print b._allsp is printing empty list in test.py? I am already loading loadsettings in the allsms.py file .
You are running loadsettings() in an if __name__ == "__main__" block:
if __name__ == "__main__":
b = SMSMgr()
b.loadsettings()
The purpose of such a block is to happen only when the code is run directly (like python allsms.py). That means it won't happen when it is imported in the line:
from SMShandler.allsms import SMSMgr
If you put the line b.loadsettings() outside of the if block, you'll see that it will already be loaded.

Categories