Have this below function.But getting error ..any thoughts ?
def zabbix_discovery(pingdom_data):
discovery = []
for k,v in data["recipes"].items():
discovery.append(
{"{#NAME}": str(v['name'])}
)
cmd_args = [
'zabbix_sender',
'-z', config.get('ZABBIX', 'server'),
'-p', config.get('ZABBIX', 'port'),
'-s', config.get('ZABBIX', 'host'),
'-k', config.get('ZABBIX', 'key1'),
'-o', "'{ \"data\": " + discovery + " }'"
]
zabbix_trapper(cmd_args)
=====
Traceback (most recent call last):
File "txncheck_backup.py", line 52, in <module>
'-o', "'{ \"data\": " + discovery + " }'"
NameError: name 'discovery' is not defined
=====
You are using discovery before it is declared on the function call.
Also, as you declare it in the function, it will be destroyed at the end of it and wont be available in the main scope.
You are trying to access it before you call the function zabbix_discovery which assigns value to it. Even if you did correct this logical mistake, you still would not be able to access the discovery variable because it is a local variable. You can either add return discovery to the end of the function and then discovery = zabbix_discovery(pingdom_data), or make it a global variable. Former would look somewhat like this:
discovery = []
def zabbix_discovery(pingdom_data):
global discovery
do what you want to do with it
zabbix_discovery(args)
Also even when you fix these things your code will throw another error because you are trying to access dictionary data in your function, which has no value assigned too. If it is assigned somewhere outside the function, you can easily fix that by adding global data in the beginning of your function.
And why do you have pingdom_data as an argument in your function if you don't use it anywhere?
Related
I define my dictionary 'frame_dict' outside my for loop. However, when it gets to my forFrame function, despite setting it has a global variable, I get an error saying that frame_dict is not defined. Any help?
import os
from imageai.Detection import VideoObjectDetection
import pickle
PATH_TO_STORE_VIDEOS = "/Users/jaime.pereira/Library/CloudStorage/OneDrive-OneWorkplace/Benchmark_Project/Videos"
tv_commercial_videos = os.listdir('Videos/')
def yolo_neural_network(path_to_videos, tv_commercials):
execution_path = os.getcwd()
frame_dict = {}
for tv_c in tv_commercials:
frame_dict.setdefault(tv_c,[])
# Use pre trained neural network to label things in videos
vid_obj_detect = VideoObjectDetection()
# Set and load Yolo model
vid_obj_detect.setModelTypeAsYOLOv3()
vid_obj_detect.setModelPath(os.path.join(execution_path,"yolov3.pt"))
vid_obj_detect.loadModel()
input_file_path = os.path.join(path_to_videos, tv_c)
if not os.path.exists("output_from_model_yolov3/"):
os.makedirs("output_from_model_yolov3/")
output_file_path = os.path.join(execution_path,"output_from_model_yolov3/", "model_yolov3_output_" + tv_c)
def forFrame(frame_number, output_array, output_count):
global frame_dict
frame_dict[tv_c].append(output_count)
return frame_dict
vid_obj_detect.detectObjectsFromVideo(
input_file_path=input_file_path,
output_file_path=output_file_path,
log_progress=True,
frame_detection_interval= 60,
minimum_percentage_probability=70,
per_frame_function=forFrame,
save_detected_video=True
)
# save dictionary
f = open("yolo_dict.pkl", "wb")
# write dict to pickle file
pickle.dump(frame_dict, f)
# close file
f.close()
return frame_dict
yolo = yolo_neural_network(PATH_TO_STORE_VIDEOS, tv_commercial_videos)
Exception has occurred: ValueError
An error occured. It may be that your input video is invalid. Ensure you specified a proper string value for 'output_file_path' is 'save_detected_video' is not False. Also ensure your per_frame, per_second, per_minute or video_complete_analysis function is properly configured to receive the right parameters.
File "/Users/jaime.pereira/Library/CloudStorage/OneDrive-OneWorkplace/Benchmark_Project/debug.py", line 35, in forFrame
frame_dict[tv_c].append(output_count)
NameError: name 'frame_dict' is not defined
During handling of the above exception, another exception occurred:
File "/Users/jaime.pereira/Library/CloudStorage/OneDrive-OneWorkplace/Benchmark_Project/debug.py", line 38, in yolo_neural_network
vid_obj_detect.detectObjectsFromVideo(
File "/Users/jaime.pereira/Library/CloudStorage/OneDrive-OneWorkplace/Benchmark_Project/debug.py", line 59, in <module>
I tried setting my frame_dict variable as global inside the forframe function expecting it to recognise it.
frame_dict is not a global, it is just in an outer scope, remove global keyword
Since you mutate the object, you don't need to do anything more:
def forFrame(frame_number, output_array, output_count):
frame_dict[tv_c].append(output_count)
return frame_dict
Since you don't assign anything to frame_dict, even if the variable were a global variable, you wouldn't need to add the global keyword if you mutate the object. global is useful only if you need to assign a new value to the variable.
The problem you are facing is that frame_dict is actually not a global variable. It is defined inside of yolo_neural_network. While this is indeed outside forFrame, it is not a global variable.
In this scenario, you should simply remove the global statement, because it is not a global variable you are importing.
I'm creating a really basic program that simulates a terminal with Python3.6, its name is Prosser(The origin is that "Prosser" sounds like "Processer" and Prosser is a command processer).
A problem that I'm having is with command import, this is, all the commands are stored in a folder called "lib" in the root folder of Prosser and inside it can have folders and files, if a folder is in the "lib" dir it can't be named as folder anymore, its name now is package(But this doesn't care for now).
The interface of the program is just a input writed:
Prosser:/home/pedro/documents/projects/prosser/-!
and the user can type a command before the text, like a normal terminal:
Prosser:/home/pedro/documents/projects/prosser/-! console.write Hello World
let's say that inside the "lib" folder exists one folder called "console" and inside it has a file called "write.py" that has the code:
class exec:
def main(args):
print(args)
As you can see the first 2 lines is like a important structure for command execution: The class "exec" is the main class for the command execution and the def "main" is the main and first function that the terminal will read and execute also pass the arguments that the user defined, after that the command will be responsible to catch any error and do what it will be created to do.
At this moment, everything is ok, but now comes the true help that I need of U guys, the command import.
Like I writed the user can type any command, and in the example above I typed a "console.write Hello World" and exists one folder called "console" and one file "write.py". The point is that the packages can be defined by a "dot", this is:
-! write Hello World
Above I only typed "write" and this says that the file is only inside the "lib" folder, it doesn't has a package to storage and separate it, so it is a Freedom command(A command that doesn't has packages or nodes).
-! console.write Hello World
Now I typed above "console.write" and this says that the file has a package or node to storage and separate it, this means that it is a Tied command(A command that has packages or nodes).
With that, a file is separated from the package(s) with a dot, the more dots you put, more folders will be navigated to find the file and proceed to the next execution.
Code
Finnaly the code. With the import statement I tryied this:
import os
import form
curDir = os.path.dirname(os.path.abspath(__file__)) # Returns the current direrctory open
while __name__ == "__main__":
c = input('Prosser:%s-! ' % (os.getcwd())).split() # Think the user typed "task.kill"
path = c[0].split('.') # Returns a list like: ["task", "kill"]
try:
args = c[1:] # Try get the command arguments
format = form.formater(args) # Just a text formatation like create a new line with "$n"
except:
args = None # If no arguments the args will just turn the None var type
pass
if os.path.exists(curDir + "/lib/" + "/".join(path) + ".py"): # If curDir+/lib/task/kill.py exists
module = __import__("lib." + '.'.join(path)) # Returns "lib.task.kill"
module.exec.main(args) # Execute the "exec" class and the def "**main**"
else:
pathlast = path[-1] # Get the last item, in this case "kill"
path.remove(path[-1]) # Remove the last item, "kill"
print('Error: Unknow command: ' + '.'.join(path) + '. >>' + pathlast + '<<') # Returns an error message like: "Error: Unknow command: task. >>kill<<"
# Reset the input interface
The problem is that when the line "module = __import__("lib." + '.'.join(path))" is executed the console prints the error:
Traceback (most recent call last):
File "/home/pedro/documents/projects/prosser/main.py", line 18, in <module>
module.exec.main(path) # Execute the "exec" class and the def "**main**"
AttributeError: module 'lib' has no attribute 'exec'
I also tried to use:
module = \_\_import\_\_(curDir + "lib." + '.'.join(path))
But it gets the same error. I think it's lighter for now. I'd like if someone help me or find some replacement of the code. :)
I think you have error here:
You have diffirent path here:
if os.path.exists(curDir + "/lib/" + "/".join(path) + ".py")
And another here, you dont have curDir:
module = __import__("lib." + '.'.join(path)) # Returns "lib.task.kill"
You should use os.path.join to build paths like this:
module = __import__(os.path.join(curdir, 'lib', path + '.py'))
def readswitch(x,y,connn,read):
x='create vlan'
y='global'
conn = sqlite3.connect('server.db')
if conn:
cur = conn.cursor()
run= cur.execute("SELECT command FROM switch WHERE function =? or type = ? ORDER BY key ASC",(x,y))
read = cur.fetchall()
return run;
import database
print (database.readswitch(x,y))
I am trying to access the database and return command in it
I make a module called database could not print it like
Traceback (most recent call last):
File "C:/Users/tommy/PycharmProjects/2015122/database.py", line 400, in <module>
import database
File "C:\Users\tommy\PycharmProjects\2015122\database.py", line 401, in <module>
print (database.readswitch(x,y))
NameError: name 'x' is not defined
and my function parameter could not be used like
def readswitch(x,y,connn,read):
PEP 8: missing whitespace after ',' Parameter 'y' value is not used
how to fix this mistake?
I am not good at python and I need help in this few hours. Thank you!
You define a function with parameter x,y and then you re-assign them within a function. That makes no sense since they are not global variable nor mutable.
I suggest you remove x,y out of function definition or move the assignment to them out to global scope (outside the function).
I'm trying to make a mixWord function and I'm getting an error saying
NameError: name 'word' is not defined
What am I missing from here?
def mixWord(word):
characterList = list(word);
print characterList
import random;
random.shuffle(characterList);
print characterList;
shuffledWord = ''.join(characterList);
print shuffledWord;
Traceback (most recent call last):
File "", line 1, in
mixWord (word)
NameError: name 'word' is not defined
The problem is PEBKAC - exactly what form, is for you to find out.
That is, the code executed is not the same as the code posted; the posted code works as expected:
def mixWord(word):
characterList = list(word);
print characterList
import random;
random.shuffle(characterList);
print characterList;
shuffledWord = ''.join(characterList);
print shuffledWord;
mixWord("PEBKAC")
So, find out why:
Has the file been saved?
Has the file been saved to the correct location?
Is the file from the correct location being run?
Is the error from different code entirely?
Also try running the code directly from an IDLE buffer as that should be immune to the previous potential issue(s).
After resolving the issue, consider updating the code to not using semicolons as they are not required here and it is un-Pythonic.
I think the problem is that you are calling mixWord(word) without defining any word variable.
I have two functions, I have placed one of the functions into a seperate .py so I can import it, but I get an error when I try to run the script.
The function that I placed into the separate .py is:
def output_messaging(message):
global myEmailText
myLogFile.write(message)
myEmailText = myEmailText + message
print message
The script that I run has the following code:
def finish_process(errors):
global myLogFile
myLogFile.close()
if errors == 0:
myEmailHeader = "Subject: **"
elif errors == 1:
myEmailHeader = "Subject: **"
else:
myEmailDestination.append("**")
#myEmailHeader = "Subject: **"
server = smtplib.SMTP(myServer) #email data log to nominated individuals
server.sendmail(myEmailSender, myEmailDestination, myEmailHeader + "\n" + myEmailText)
server.quit()
When I run the script i get the following error.
NameError: global name 'myLogFile' is not defined
myLogFile is declared lower down in the code (which is the location of the log file), but I'm slightly confused.
Thanks
The error is clear. myLogFile is not defined anywhere in your output_messaging function. You need to define it in that function, or pass it in as a parameter.
You shouldn't be using globals anyway, they are almost always a bad idea. Pass parameters explicitly.
In output_messaging, you don't have global myLogFile to indicate that myLogFile is defined somewhere else in the file. When Python runs that function, it doesn't recognize the variable now.
Note that global variables are generally discouraged but that's a different discussion.