python function's parameter could not use and one print error - python

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).

Related

variable inside function not defined despite having it defined globally

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.

My question is about the functionality of the 'eval' function when this is included in a function of an imported module

I have created a simple function for reporting current values of variables in some engineering scripts, by passing the variable name in an eval() function. The argument is passed as string then the eval() reads it and reports back the value with some additional info. The function works properly in a single script. However when i am importing the same function from a module i get back an error saying that the variable has is not defined.
I have trying setting it up as a global variable but still get the same problem
def report(name,units = '-',comment ='NC'):
if type(eval(name)) == str:
print('{0:<12}= {1:^10} {2:^5} {3}'.format(name,eval(name),units,comment))
else:
print('{0:<12}= {1:8.3f} {2:^5} {3}'.format(name,eval(name),units,comment))
While trying to use the function from the imported module i get the following
>>>from reporting import*
>>> from shapes import*
>>> Iyy = rec_Iyy(40,60)
>>> report('Iyy')
Traceback (most recent call last):
File "<pyshell>", line 1, in <module>
File "C:\Users\vousvoukisi\OneDrive\11.Python\03_myScripts\design_mod\reporting.py", line 8, in report
if type(eval(name)) == str:
File "<string>", line 1, in <module>
NameError: name 'Iyy' is not defined
## while i would expect the outcome to be :
>>> %Run reporting.py
Iyy = 720000.000 - NC

PythonNameError: name 'discovery' is not defined

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?

input() causes unexpected EOF SyntaxError

I have written a return function for my group project.
I am using python 3.4 and wrote this:
def readrouter(x, y):
conn = sqlite3.connect('server.db')
cur = conn.cursor()
cur.execute("SELECT DISTINCT command FROM router WHERE
function =? or type = ? ORDER BY key ASC",(x, y))
read = cur.fetchall()
return read;
a = input("x:")
b = input("y:")
for result in readrouter(a,b):
print (result[0])
As my major member is using 2.7 and I need to follow his version now.
After I re-input my .py into python 2.7
there is a error:
x:create vlan
Traceback (most recent call last):
File "C:/Users/f0449492/Desktop/2015225/database.py", line 322, in <module>
a = input("x")
File "<string>", line 1
create vlan
^
SyntaxError: unexpected EOF while parsing
Process finished with exit code 1
how to fix this bug?
In Python 2.7, replace input() with raw_input().
The former runs eval() on the input string and expects valid Python code as input. Your input create vlan isn't valid Python and can't be eval'ed. The latter just returns a string with no further processing.
As a follow up - to ensure compatibility with both Python branches you may use six .

Python - TypeError: argument of type 'function' is not iterable

I'm running some python code and get an error:
Exception in Tkinter callback
Traceback (most recent call last):
File "/usr/lib/python2.7/lib-tk/Tkinter.py", line 1413, in __call__
return self.func(*args)
File "multiline14.py", line 28, in getText
if encodinghex in process:
TypeError: argument of type 'function' is not iterable
My def is below.
def gui(item):
def default_encode(s):
pass
# map items from menu to commands
encodinghex = '.encode("hex")'
decodinghex = '.decode("hex")'
mapping = {"encode_b64": base64.encodestring,"encode_url": urllib.quote_plus,"encode_hex": encodinghex, "decode_b64": base64.decodestring, "decode_url": urllib.unquote_plus, "decode_hex": decodinghex}
process = mapping.get(item, default_encode)
def getText():
#clear bottom text field
bottomtext.delete(1.0, END)
#var equals whats in middle
var = middletext.get(1.0, 'end-1c')
#insert encoded var in bottom
if encodinghex in process:
var = '"%s"' % (var)
bottomtext.insert(INSERT, eval(var + process))
elif decodinghex in process:
var = '"%s"' % (var)
bottomtext.insert(INSERT, eval(var + process))
else:
bottomtext.insert(INSERT, process(var))
What causes that error?
You are requesting a function from mapping here:
process = mapping.get(item, default_encode)
You then try and iterate it here:
if encodinghex in process:
You can't use the in keyword unless the subject is Iterable.
What you're trying to achieve here is to actually see which function your call to mapping.get() returned
if process == encodinghex:
Note that base64.encodestring, urllib.quote_plus, encodinghex, base64.decodestring, urllib.unquote_plus, decodinghex are all functions
What you've done doesn't seem to make any sense at all. You have two text strings, encodinghex and decodinghex, which you're using eval to turn into code to execute. But in your mapping dict alongside those you've also got various actual methods, which you're also trying to pass to eval - which is bound to fail in itself, but even before that your code is trying to add the existing text string to the actual function value, which is impossible.
Judging from the last line of your sample, you have a function called process() somewhere. Yet you try to access it as if it were an iterable in the line if encodinghex in process. To fix the error, change the name of either the function or the iterable.

Categories

Resources