I am simply trying to receive an input, run it through some if, elif conditions and replace certain text from a bunch of lines :
def task(appdynhost):
if (appdynhost) == "security":
appdynpass = 'xxxxxxxx'
elif (appdynhost) == "security2":
appdynpass = 'yyyyyyyy'
elif (appdynhost) == "security3":
appdynpass = 'zzzzzzzz'
elif (appdynhost) == "security4":
appdynpass = 'wwwwwwww'
replacements = {'<controller_name>':appdynhost,'<controller_password>';appdynpass}
s = r"""
"standardenv::v2_0_0_0_0":
"appgroups::v1_0_0_0_0":
definitions:
jdk: {gid: 5007}
app: {gid: 5008}
"appusers::v1_0_0_0_0":
definitions:
jdk: {group: jdk, uid: 5007}
app: {group: app, uid: 5008}
"jdk::v1_7_45_2_0::standard":
instance_owner: jdk
instance_group: jdk
"app::v1_1_2_1_0::standard":
instance_owner: app
instance_group: app
controller_host: "<controller_name>.saas.com"
account_name: "<controller_name>"
account_password: "<controller_password>" """
line=s.split()
for line in s.splitlines():
for src, target in replacements.iteritems():
line = line.replace(src, target)
lines.append(line)
with open('DC_mcp.yaml', 'w') as outfile:
for line in lines:
outfile.write(line + '\n')
print (line)
I am getting this error :
Traceback (most recent call last):
File "build/bdist.linux-x86_64/egg/bdblib/task_runner.py", line 72, in run_bdblib_task
File "build/bdist.linux-x86_64/egg/bdblib/run.py", line 38, in run
return task_module.task(env, **inputs)
TypeError: task() got multiple values for keyword argument 'appdynhost'
I am getting the input for appdynhost as a raw input. I am not sure whats going wrong.
You definition of "task" function only has one argument which you named "appdynhost".
def task(appdynhost):
...
Your call however has several:
return task_module.task(env, **inputs)
TypeError: task() got multiple values for keyword argument 'appdynhost'
At either the function or the call you'll need to fix the inputs.
Related
I am trying to make the code cleaner and better manageable and i wanted to start with reading a cisco file. However when i try to put it in a function, it is not able to give me the outputs. The same works perfectly out of a function
Working model
parse = CiscoConfParse("C:\\python\\mydata\\TestConfigFile.txt")
TCPSrv = parse.find_objects("service\stcp\sdestination\seq")
UDPSrv = parse.find_objects("service\sudp\sdestination\seq")
ObjectNetwork = parse.find_objects("^object\snetwork\s")
ObjectGroupSrv = parse.find_objects("^object-group\sservice")
ObjectGroupNetwork = parse.find_objects("^object-group\snetwork\s")
This creates a list for all the above like the one below
TCPSrv = [<IOSCfgLine # 83 ' service tcp destination eq https' (parent is # 82)>,<IOSCfgLine # 97 ' service tcp destination eq www '(parent is # 102)>]
But when i put this into a function, it does not work. This is the first time i am trying out to use functions, and I know that i am doing something wrong.
This is my code for Functions
def cisco(filename):
parse = CiscoConfParse(filename)
TCPSrv = parse.find_objects("service\stcp\sdestination\seq")
UDPSrv = parse.find_objects("service\sudp\sdestination\seq")
ObjectNetwork = parse.find_objects("^object\snetwork\s")
ObjectGroupSrv = parse.find_objects("^object-group\sservice")
ObjectGroupNetwork = parse.find_objects("^object-group\snetwork\s")
return TCPSrv, UDPSrv, ObjectNetwork, ObjectGroupSrv, ObjectGroupNetwork
file = C:\\python\\mydata\\TestConfigFile.txt
cisco(file)
This does not give any output.
>>> TCPSrc
Traceback (most recent call last):
File "<input>", line 1, in <module>
NameError: name 'TCPSrc' is not defined
I have tried putting it like this below also
cisco("C:\\python\\mydata\\TestConfigFile.txt")
Can someone kindly assist what I am doing wrong.
This does not give any output
>>> TCPSrc
Traceback (most recent call last):
File "", line 1, in
NameError: name 'TCPSrc' is not defined
You have not assigned the return values to anything. When you call cisco(), you need to assign the return values to something... please use:
from ciscoconfparse import CiscoConfParse
def cisco(filename):
parse = CiscoConfParse(filename)
TCPSrv = parse.find_objects("service\stcp\sdestination\seq")
UDPSrv = parse.find_objects("service\sudp\sdestination\seq")
ObjectNetwork = parse.find_objects("^object\snetwork\s")
ObjectGroupSrv = parse.find_objects("^object-group\sservice")
ObjectGroupNetwork = parse.find_objects("^object-group\snetwork\s")
return TCPSrv, UDPSrv, ObjectNetwork, ObjectGroupSrv, ObjectGroupNetwork
values = cisco("C:\\python\\mydata\\TestConfigFile.txt")
TCPsrv = values[0]
UDPsrv = values[1]
# ... etc unpack the remaining values as illustrated above
Im brand new to python and coding, im trying to get below working.
this is test code and if I can get this working I should be able to build on it.
Like I said im new to this so sorry if its a silly mistake.
# coding=utf-8
import ops # Import the OPS module.
import sys # Import the sys module.
import re
# Subscription processing function
def ops_condition (o):
enter code herestatus, err_str = o.timer.relative("tag",10)
return status
def ops_execute (o):
handle, err_desp = o.cli.open()
print("OPS opens the process of command:",err_desp)
result, n11, n21 = o.cli.execute(handle,"return")
result, n11, n21 = o.cli.execute(handle,"display interface brief | include Ethernet0/0/1")
match = re.search(r"Ethernet0/0/1\s*(\S+)\s*", result)
if not match:
print("Could not determine the state.")
return 0
physical_state = match[1] # Gets the first group from the match.
print (physical_state)
if physical_state == "down":
print("down")
result = o.cli.close(handle)
else :
print("up")
return 0
Error
<setup>('OPS opens the process of command:', 'success')
Oct 17 2018 11:53:39+00:00 setup %%01OPSA/3/OPS_RESULT_EXCEPTION(l)[4]:Script is test.py, current event is tag, instance is 1515334652, exception reason is Trac eback (most recent call last):
File ".lib/frame.py", line 114, in <module>
ret = m.ops_execute(o)
File "flash:$_user/test.py", line 22, in ops_execute
physical_state = match[1] # Gets the first group from the match.
TypeError: '_sre.SRE_Match' object has no attribute '__getitem__'
The __getitem__ method for the regex match objects was only added since Python 3.6. If you're using an earlier version, you can use the group method instead.
Change:
physical_state = match[1]
to:
physical_state = match.group(1)
Please refer to the documentation for details.
The seemingly simple code below throws the following error:
Traceback (most recent call last):
File "/home/nirmal/process.py", line 165, in <module>
'time_diff': f.last(adf['time_diff']).over(window_device_rows)
TypeError: __call__() got an unexpected keyword argument 'this_campaign'
Code:
# Function to flag network timeouts
def flag_network_timeout(**kwargs):
if kwargs['this_network'] != kwargs['last_network'] \
or kwargs['this_campaign'] != kwargs['last_campaign'] \
or kwargs['this_adgroup'] != kwargs['last_adgroup'] \
or kwargs['this_creative'] != kwargs['last_creative'] \
or kwargs['time_diff'] > network_timeout:
return 1
else:
return 0
flag_network_timeout = f.udf(flag_network_timeout, IntegerType())
# Column spec to go over the device events and flag network resets
network_timeout_flag = flag_network_timeout(**{
'last_network': f.first(adf['network']).over(window_device_rows),
'last_campaign': f.first(adf['campaign']).over(window_device_rows),
'last_adgroup': f.first(adf['adgroup']).over(window_device_rows),
'last_creative': f.first(adf['creative']).over(window_device_rows),
'this_network': f.last(adf['network']).over(window_device_rows),
'this_campaign': f.last(adf['campaign']).over(window_device_rows),
'this_adgroup': f.last(adf['adgroup']).over(window_device_rows),
'this_creative': f.last(adf['creative']).over(window_device_rows),
'time_diff': f.last(adf['time_diff']).over(window_device_rows)
})
# Update dataframe with the new columns
adf = adf.select('*', network_timeout_flag.alias('network_timeout'))
What am I doing wrong please? Thank you.
You get an exception because UserDefinedFunction.__call__ supports only varargs and not keyword args.
def __call__(self, *cols):
sc = SparkContext._active_spark_context
jc = self._judf.apply(_to_seq(sc, cols, _to_java_column))
return Column(jc)
At much more basic level UDF can receive only Column arguments, which will be expanded to their corresponding value on runtime, and not standard Python objects.
Personally I wouldn't use **kwargs for this at all, but ignoring that you can achieve what you want by composing SQL expressions:
def flag_network_timeout_(**kwargs):
cond = (
(kwargs['this_network'] != kwargs['last_network']) |
(kwargs['this_campaign'] != kwargs['last_campaign']) |
(kwargs['this_adgroup'] != kwargs['last_adgroup']) |
(kwargs['this_creative'] != kwargs['last_creative']) |
(kwargs['time_diff'] > network_timeout))
return f.when(cond, 1).otherwise(0)
I've got simple python functions.
def readMainTemplate(templateFile):
template = open(templateFile, 'r')
data = template.read()
index1 = data.index['['] #originally I passed it into data[]
index2 = data.index[']']
template.close()
return data[index1:index2]
def writeMainTemplate(template, name):
file = open(name, 'w')
file.write(template)
file.close()
#runMainTemplate('main.template')
def runMainTemplate(template):
code = readMainTemplate(template)
writeMainTemplate(code, 'main.cpp')
They basically suppose to read from file some kind of template(something like this)
--template "main"
[
#include <iostream>
using namespace std;
int main()
{
return 0;
}
]
and then write it to file(basically generating main.cpp template)
I run it from command line using this command
python -c "from genmain import runMainTemplate; runMainTemplate('main.template')"
but I've got this error
Traceback (most recent call last):
File "<string>", line 1, in <module>
File "genmain.py", line 18, in runMainTemplate
code = readMainTemplate(template)
File "genmain.py", line 6, in readMainTemplate
index1 = data.index['['] #originally I passed it into data[]
TypeError: 'builtin_function_or_method' object has no attribute '__getitem__'
I thought that data = template.read() supposed to return string and string should allow to perform operation slicing [:].
But why there is an error?
Also a question: where I should put python scripts in order to run it anywhere in filesystem?(I want to generate file anywhere in the filesystem in the current folder by providing path to the template)
The problem is that index is a method and needs to be called with () not []. To use Kasra's example:
>>> s="aeer"
>>> s.index('a')
0
from PIL import Image
import input_class
import input_function
import input_crop_values
import input_translate
class ImageChanger():
def __init__ ():
image_filename = input_class.input_file_name()
self.my_image = Image.open(image_filename)
chosen_Function = input_function.input_vaild_function()
if chosen_Function == "Crop" or chosen_Function == "crop":
crop_values = input_crop_values.input_crop_data()
my_image.crop(crop_values)
elif chosen_Function == "Translate" or chosen_function == "translate":
translate_values = input_translate.input_translate_data()
my_image.crop(translate_values)
else:
print("unexpected error while running code")
def printState():
print( "Your image file name is %s" % self.my_filename );
return (self.my_filename);
def translate(self,x_cord,y_cord):
return (self.my_image.offset(x_cord,y_cord));
def crop(self, box):
return (self.my_image.crop(box))
sorry for odd formatting,
Error:
Traceback (most recent call last):
File "C:\Users\Alexander\Desktop\Final_Udacity_project\dragon_picture_test.py", line 1, in <module>
import picture_changer
File "C:\Users\Alexander\Desktop\Final_Udacity_project\picture_changer.py", line 3, in <module>
import input_function
File "C:\Users\Alexander\Desktop\Final_Udacity_project\input_function.py", line 14
else
^
SyntaxError: invalid syntax
I have some other functions, not listed that use the input command sort of like a user interface, then it returns it to the larger class.
The places that the values are returned and what is return is:
line 8*: image_filename = input_class.input_file_name() # you would give a name of a picture here,
line 10*: chosen_function = input_function.input_vaild_function() # you Would give it either crop or translate can be sentence case or lowercase
line 11*: crop_values = input_crop_values.input_crop_data() # you would give it data in brackets like [1,2,3,4] and it would crop it.
line 15*: translate_values = input_translate.input_translate_data() # you would give it information in ( ), like (1,2,3,4) and it would translate it.
The code is acting really weird with the Boolean and the error message isn't helping me that much.
else, like other statements that come before a block, requires a colon.
else: