Change directory to each value of list - python

I am writing the below code:
connect('user', 'password', url='t3://host:1234')
domainConfig()
cd("JDBCSystemResources")
dataSources = cmo.getJDBCSystemResources()
if [len(dataSources) >0]:
mylist = []
for dataSource in dataSources:
dsName = dataSource.getName()
mylist.append(str(dsName))
mylist_len=len(mylist)
y=1
while(y <= mylist_len):
for dir in mylist:
cd(os.path.join(dir+'/JDBCResource/'+dir+'/JDBCResource/'+dir))
max_value = cmo.getMaxCapacity()
print dir+'='+str(max_cap)
cd('/')
y = y + 1
when I execute this code, it cd to only first value of the list and give this error
EssXADS=100
This Exception occurred at Sat Aug 21 08:41:53 UTC 2021.
javax.management.AttributeNotFoundException:
com.bea:Name=EssXADS,Location=FADomain,Type=weblogic.j2ee.descriptor.wl.JDBCConnectionPoolParamsBean,Parent=[FADomain]/JDBCSystemResources[EssXADS],Path=JDBCResource[EssXADS]/JDBCConnectionPoolParams:mds-ESS_MDS_DS
Problem invoking WLST - Traceback (innermost last): File
"/tmp/data_source_status_new.py.FS_bkp", line 16, in ? File
"", line 182, in cd File "", line 1878, in
raiseWLSTException WLSTException: Error cding to the MBean
Please help me to change the directory and perform the action on every value of list. I am running this on weblogic prompt.

you could use the os.path.join() function for this.
In your code it would look something like this,
for dir in mylist:
cd(os.path.join(dir,"some_dir",dir,"some_dir",dir))

Related

Can't run a python script ('str' object is not callable)

I am trying to make a python program, that will help me read notifications log easily.
Here's the code:-
location=open("/home/pika/.cache/xfce4/notifyd/log","rt")
data=location.read()
l_data=list(data) #Contents of log file is in string now, in data variable
x=data.count('app_name')
def rm(start,stop,p_name):
for x in range(start,stop+1):
print(x)
n=p_name(x)
m=l_data.remove(n)
print(m)
data=''
data=data.join(l_data)
for i in range(0,x):
#Time of notification
t_start=data.index('[')
t_end=data.index(']')
t=data[t_start:t_end+1]
print(t)
print('\n')
rm(t_start,t_end,t)
#Name of the application
name_start=data.index('app_name')
name_end=data.index('summary')
name=data[name_start:name_end-1]
print(name)
print('\n')
rm(name_start,name_end,name)
#Heading of notification
head_start=data.index('body')
head_end=data.index('app_icon')
head=data[head_start:head_end-1]
print(head)
print('\n')
rm(head_start,head_end,head)
print('-----------------------------------------------------------')
But, it is giving me the following error:-
[2020-07-23T16:24:43]
0
Traceback (most recent call last):
File "New File.py", line 20, in <module>
rm(t_start,t_end,t)
File "New File.py", line 8, in rm
n=p_name(x)
TypeError: 'str' object is not callable
Any idea what's the issue?
(p.s. i am new to programming, sorry for messy code)
p_name is a list. So you need to use square brackets:
n=p_name[x]
You called the function rm() with last parameter p_name as a string.
t=data[t_start:t_end+1] # this is a string
rm(t_start,t_end, t) # t is a string
Inside the function you assign n = p_name(x) which causes the error.
Did you mean n = p_name[x]?

domainruntime() and CD('/') issue

I created a python file and created another shell file to prepare the environment to run the python script. Below is part of the python script including two functions and the error code.
I have the following Python code
def getState():
print "Getting Servers status..."
cd ('/')
allModules = cmo.getServers()
domainRuntime()
cnt = 0
modules = ""
for moduleName in allModules:
currentModule = moduleName.getName()
print ":: Current Server Name = " + currentModule
cd ('/')
slrBean = cmo.lookupServerLifeCycleRuntime(currentModule)
serverState = slrBean.getState()
print "Current Server status is: " + serverState
if serverState == "RUNNING" and (currentModule.find("amq")) != -1:
print "Shutting down AMQ managed server"
shutdown(currentModule, 'Server', 'true', 1000, force="true", block='true')
undeployApp()
ds(currentModule,moduleName)
elif (currentModule.find("amq")) != -1:
try:
print "ElseIf"
undeployApp()
except Exception, e:
print e
ds(currentModule,moduleName)
if (cnt == 0):
modules = currentModule
else:
modules = modules + "," + currentModule
cnt = cnt + 1
return modules
def ds(myModule,mo):
print "Deleting AMQ server"
cd('/Servers/'+myModule)
cmo.setCluster(None)
cmo.setMachine(None)
editService.getConfigurationManager().removeReferencesToBean(getMBean('/Servers/'+myModule))
cd('/')
cmo.destroyServer(getMBean('/Servers/'+myModule))
I am getting this error
Deleting AMQ server
This Exception occurred at Mon Oct 07 08:24:52 PDT 2019.
javax.management.AttributeNotFoundException: com.bea:Name=gems,Type=DomainRuntime:Servers
Problem invoking WLST - Traceback (innermost last):
File "/x/home/pegaadmin/test.py", line 233, in ?
File "/x/home/pegaadmin/test.py", line 107, in getState
File "/x/home/pegaadmin/test.py", line 118, in ds
File "<iostream>", line 164, in cd
File "<iostream>", line 552, in raiseWLSTException
WLSTException: Error cding to the MBean
Configuration failied, aborting .....
I can't figure out the domainruntime() and the correct path CD('/')
any solutions and suggestions please ?!

open function not returning file descriptor

Python open function does not return file descriptor. Why could this be? I am using python 3.3.
test_file_open.py
#!/usr/bin/env python
import sys
if __name__ == '__main__':
html = ""
hmtl_fd = open("ns_temp.html",'r')
for line in html_fd:
html += line
Output:
Traceback (most recent call last):
File "./test_file_open.py", line 7, in <module>
for line in html_fd:
NameError: name 'html_fd' is not defined
Permissions:
-rwxr-xr-x 1 michael michael 160 Mar 16 23:03 test_file_open.py
There is a typo in a variable name, see hmtl_fd and html_fd.
Replace:
hmtl_fd = open("ns_temp.html",'r')
with:
html_fd = open("ns_temp.html",'r')
Typo: hmtl_fd in place of html_fd

how to use facet in pysolr

I have successful built a python search app with pysolr. So far I have used two fields: id and title. now i want to push two different versions of titles; the original and the title after removing the stopwords. any ideas? the following code works:
def BuildSolrIndex(solr, trandata):
tmp = []
for i, dat in enumerate(trandata):
if all(d is not None and len(d) > 0 for d in dat):
d = {}
d["id"] = dat[0]
d["title"] = dat[1]
tmp.append(d)
solr.add(tmp)
solr.optimize()
return solr
but this one does not:
def BuildSolrIndex(solr, trandata):
tmp = []
for i, dat in enumerate(trandata):
if all(d is not None and len(d) > 0 for d in dat):
d = {}
d["id"] = dat[0]
d["title_org"] = dat[1]
d["title_new"] = CleanUpTitle(dat[1])
tmp.append(d)
solr.add(tmp)
solr.optimize()
return solr
Any ideas?
EDIT:
bellow is the exception:
Traceback (most recent call last):
...
solr = BuildSolrIndex(solr, trandata)
File "...", line 56, in BuildSolrIndex
solr.add(tmp)
File "build/bdist.linux-x86_64/egg/pysolr.py", line 779, in add
File "build/bdist.linux-x86_64/egg/pysolr.py", line 387, in _update
File "build/bdist.linux-x86_64/egg/pysolr.py", line 321, in _send_request
pysolr.SolrError: [Reason: None]
<response><lst name="responseHeader"><int name="status">400</int><int name="QTime">8</int></lst><lst name="error"><str name="msg">ERROR: [doc=...] unknown field 'title_new'</str><int name="code">400</int></lst></response>
This looks like an issue with your Solr schema.xml, as the exception indicates that "title_new" is not recognized as a valid field. This answer may be of assistance to you: https://stackoverflow.com/a/14400137/1675729
Check to make sure your schema.xml contains a "title_new" field, and that you've restarted the Solr services if necessary. If this doesn't solve your problem, come on back!

Python NameError when var IS most definitely defined

def make_pdf(self):
self.get_filez()
self.get_client()
file_name = self.client_id+"_"+self.client_name+"_"+self.batch_num
style = libxslt.parseStylesheetDoc(self.xsl_file)
transformation = style.applyStylesheet(self.xml_file,None)
style.saveResultToFilename("tmp/"+file_name+".fo",transformation,0)
style.freeStylesheet()
self.xml_file.freeDoc()
transformation.freeDoc()
fop_cmd = "/usr/bin/xmlgraphics-fop"
#file_name = self.tpa+"_"+self.be+"_"+self.batch_num
cmd = [fop_cmd,"-fo","tmp/"+file_name+".fo","-pdf","tmp/"+file_name+".pdf"]
#fop_transform = subprocess.Popen(cmd,stdout=subprocess.PIPE,stderr=subprocess.STDOUT)
#fop_log = "-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-\n"
#fop_log = fop_log + time.strftime('%Y-%m-%d %R:%S')+"\n"
#fop_log = fop_log + file_name+".fo" + "\n"
#fop_log = fop_transform.communicate()[0]+"\n"
#f = open("/tmp/error_log","a")
#f.write(fop_log)
#f.close()
OK If I comment out the cmd variable declaration the code runs and makes an fo file correctly. With is uncommented like it is above, I get a NameError on file_name is not defined (which it is in the top). If I uncomment the second declaration of file_name right above the cmd declaratioin, it thows a NameError on self. '.' In the past when this sort of thing happens, it is a syntax error. I am missing it, please helpz!
When the second declaration of file_name is commented out:
Traceback (most recent call last):
File "make_pdfs.py", line 11, in ?
from MakePdfs import MakePdfs
File "/home/khouser/removed/removed/MakePdfs.py", line 16, in ?
class MakePdfs:
File "/home/khouser/removed/removed/MakePdfs.py", line 39, in MakePdfs
cmd = [fop_cmd,"-fo","tmp/"+file_name+".fo","-pdf","tmp/"+file_name+".pdf"]
NameError: name 'file_name' is not defined
When the second declaration of file_name is uncommented:
Traceback (most recent call last):
File "make_pdfs.py", line 11, in ?
from MakePdfs import MakePdfs
File "/home/khouser/removed/removed/MakePdfs.py", line 16, in ?
class MakePdfs:
File "/home/khouser/removed/removed/MakePdfs.py", line 38, in MakePdfs
file_name = self.tpa+"_"+self.be+"_"+self.batch_num
NameError: name 'self' is not defined
Mysterious NameErrors may arise from your file containing invisible control characters. On unix machines, you can spot these errors by looking at the output of
cat -A filename.py
Try to print file_name after each line, to see if somebody is removing the "file_name" variable from your namespace.
In addition, to be more pythonic (and efficient), use
file_name = "_".join((self.client_id, self.client_name, self.batch_num))
to concatenate strings.
If you're assigning file_name here:
file_name = self.client_id+"_"+self.client_name+"_"+self.batch_num
And you're getting a NameError reporting, that file_name is not defined, then try wrapping the operation in a try..except, to see what is going wrong:
try:
file_name = self.client_id+"_"+self.client_name+"_"+self.batch_num
except NameError as err:
print err, 'failed, here is some debug stuff:'
print "CLIENT ID =", self.client_id
print "CLIENT NAME =", self.client_name
print "BATCH NUM =", self.batch_num
If any of this is failing, this will set you on the course to finding out why and narrowing down the cause of it.

Categories

Resources