How to use list data as variable - python

I need to use list value as variable. How could it be done.
comp_list = [ "list1", " list2", "list3"]
for comp in comp_list:
print (comp)
cmd = 'ps -aef | grep $comp'<<<<
print (cmd)
status, command = getstatusoutput(cmd)
the <<< directing to $comp should be replaced by list1 and then list2 and it should go on.

cmd = 'ps -aef | grep $comp'<<<<
This could be done like this:
cmd = 'ps -aef | grep %s' % comp

You could either use str.format:
cmd = 'ps -aef | grep {}'.format(comp)
Or just concatenate strings:
cmd = 'ps -aef | grep ' + comp

Related

greping with os command assigning it in tupe want to remove /t

args = parser.parse_args()
find = args.data_variable
cmd = commands.getoutput("cat /cc/ddd '"+find+"' |grep -A 3 node | tail -n +2")
r = tuple(cldb.split('\n'))
print r
i get the out put in tuples but it has /t please help how to remove it.
Use str.strip()
Ex:
cldb = ('\t\tm\mrcg1234', '\t\tmrcg1235', '\t\tmrcg1235.me.com')
cldb = tuple([i.strip() for i in cldb])
print(cldb)
Output:
('m\\mrcg1234', 'mrcg1235', 'mrcg1235.me.com')

Getting Python to print to the command line (the output of the graphviz command gvpr)

I'm trying to get Python to run this command, which runs fine from my command prompt:
ccomps -x rel_graph.dot | gvpr -c "N[nNodes($G)<5]{delete(0,$)}" | dot | gvpack | sfdp -Goverlap=prism | gvmap -e | gvpr "BEGIN{int m,w,e = 0} N[fontcolor=='blue']{m += 1} N[fontcolor=='green']{e += 1} N[fontcolor=='red']{w += 1} END{print(m); print(w); print(e);}"
In Python, I'm using:
temp = subprocess.Popen("""ccomps -x rel_graph.dot | gvpr -c \
"N[nNodes($G)<5]{delete(0,$)}" | dot | gvpack | sfdp -Goverlap=prism \
| gvmap -e | gvpr 'BEGIN{int m,w,e = 0} \
N[fontcolor=="blue"]{m += 1} \
N[fontcolor=="green"]{e += 1} \
N[fontcolor=="red"]{w += 1} \
END{print(m); print(w); print(e);}'
""", shell=True, stdout=subprocess.PIPE, stderr=subprocess.STDOUT)
...and then read/print lines from temp. The issue is that Python doesn't print the three last print statements (all are integers) to standard output, or at least I wasn't able to find it. The rest of the gvpr program works fine from Python.
Thanks!
After some more work I changed the BEGIN quotation marks to double, and all the internal arguments to single, and that seems to have solved the issue.
You can send the stdout \ stderr to files likes this -
from subprocess import Popen
std_out_file = "/tmp/stdout.log"
std_err_file = "/tmp/stderr.log"
command_to_execute = "<your-command>"
with open(std_out_file, "wb") as out, open(std_err_file, "wb") as err:
p = Popen(command_to_execute, shell=True, cwd=<folder>, stdout=out, stderr=err)
p.communicate()
Then you read the stdout \ stderr from the files, for example:
f = open(std_out_file, "r")
stdout = f.readlines()
f.close()
You can check the return code of the command, to check if you also need to print the stderr like this -
if p.returncode == 0:

Script returns output in IDLE not when executed at CLI

I have a script that runs a few external commands and returns their values. I am able to run the script within IDLE just fine, and I get the expected results.
When I execute the script in a Linux shell (Bash), it runs, but with no output.
The exit status is 0.
#!/usr/bin/python
import array,os,subprocess
def vsdIndex(vmVsd):
index = subprocess.call(["/root/indeces.sh", vmVsd], stdout=subprocess.PIPE, shell=TRUE).communicate()[0]
print index
return (firstSerial,lastSerial)
def main():
vsdArray = []
vsdProc = subprocess.Popen(["sc vsd show | tail -n +2 | grep -Ev 'iso|ISO|vfd' | awk '{{print $1}}'"], stdout=subprocess.PIPE, stderr=subprocess.PIPE).communicate()[0]
while True:
line = vsdProc.stdout.readline()
if line != '':
vsdIndex(line)
print "VSD:", line.rstrip()
print firstSerial
print lastSerial
else:
break
If I simplify it, and run without the function, I have the same behaviour:
def main():
vsdArray = []
vsdProc = subprocess.Popen(["sc vsd show | tail -n +2 | grep -Ev 'iso|ISO|vfd' | awk '{{print $1}}'"], stdout=subprocess.PIPE, stderr=subprocess.PIPE).communicate()[0]
while True:
line = vsdProc.stdout.readline()
if line != '':
print "VSD:", line.rstrip()
else:
break
You need to call your main() function. Here is a common way of doing that automatically when you run on the command line:
if __name__ == "__main__":
main()

Using grep in log file

How do i place grep in the below string. I seem to be not getting it right.
p = subprocess.Popen(["tail", "-10", "/datax/qantas/run/tomcat/logs/localhost_access_log.2016-02-29.txt" "|" "grep /checkout-qantas/int/price?"], stdout=subprocess.PIPE)
gives me
tail: cannot open /datax/qantas/run/tomcat/logs/localhost_access_log.2016-02-29.txt|grep /checkout-qantas/int/price?' for reading: No such file or directory
shell = True and putting your complete command in quote should help you-
p = subprocess.Popen('tail -10 /datax/qantas/run/tomcat/logs/localhost_access_log.2016-02-29.txt | grep /checkout-qantas/int/price?', stdout=subprocess.PIPE, shell = True)
You have used shell keyword pipe (|), so you need to set shell=True:
subprocess.Popen("tail -10 ... | grep ....", shell=True)
If you want to save the output:
out = subprocess.check_output("tail -10 ... | grep ....", shell=True)
Better not to use shell=True, use subprocess.PIPE instead e.g.:
>>> out = subprocess.Popen(['tail', '-10', '/var/log/syslog'], stdout=subprocess.PIPE)
>>> subprocess.check_call(['grep', 'UDP'], stdin=out.stdout)

python + run system command with variables

I need to run system command from python
I have python - version - Python 2.4.3
I try the following , in this example ls -ltr | grep Aug
#!/usr/bin/python
import commands
Month = "Aug"
status,output = commands.getstatusoutput(" ls -ltr | grep Month " )
print output
how to insert the Month variable in the command ?
so grep will do that
| grep Aug
I try this also
status,output = commands.getstatusoutput( " ls -ltr | grep {} ".format(Month) )
but I get the following error
Traceback (most recent call last):
File "./stamm.py", line 14, in ?
status,output = commands.getstatusoutput( " ls -ltr | grep {} ".format(Month) )
AttributeError: 'str' object has no attribute 'format'
import commands
Month = "Aug"
status,output = commands.getstatusoutput(" ls -ltr | grep '" + Month + "'")
print output
Or a couple other possibilites are:
status,output = commands.getstatusoutput("ls -ltr | grep '%s'" % Month)
or
status,output = commands.getstatusoutput(" ls -ltr | grep \"" + Month + "\"")
You don't need to run the shell, there is subprocess module in Python 2.4:
#!/usr/bin/env python
from subprocess import Popen, PIPE
Month = "Aug"
grep = Popen(['grep', Month], stdin=PIPE, stdout=PIPE)
ls = Popen(['ls', '-ltr'], stdout=grep.stdin)
output = grep.communicate()[0]
statuses = [ls.wait(), grep.returncode]
See How do I use subprocess.Popen to connect multiple processes by pipes?
Note: you could implement it in pure Python:
#!/usr/bin/env python
import os
from datetime import datetime
def month(filename):
return datetime.fromtimestamp(os.path.getmtime(filename)).month
Aug = 8
files = [f for f in os.listdir('.') if month(f) == Aug]
print(files)
See also, How do you get a directory listing sorted by creation date in python?

Categories

Resources