1

I use this command string to get the percentage value of the CPU utilization.

top -d 0.5 -b -n2 | grep 'Cpu(s)'|tail -n 1 | awk '{result = $2 + $4} END {printf "%3.0f\n", result'}

In the shell it works, but I need to execute it out of a python script.

This does not work because of the "%3.0f\n" part.

p = subprocess.Popen("top -d 0.5 -b -n2 | grep 'Cpu(s)'|tail -n 1 | awk '{result = $2 + $4} END {printf "%3.0f\n", result'}", stdout=subprocess.PIPE, shell=True) 

How can I realize the padding to 3 characters and rounding up in this scenario?

I think the masking is the problem.

But maybe there is another way, which is better suited?

Thanks for any help!

Update: The solution was using tripple quotes:

p = subprocess.Popen('''top -d 0.5 -b -n2 | grep 'Cpu(s)'|tail -n 1 | awk '{result = $2 + $4} END {printf "%3.0f", result'}''', stdout=subprocess.PIPE, shell=True) 
Neverland
  • 773
  • 2
  • 8
  • 24
  • This does not solve your problem, but reduces number of commands needed to run. `top -d 0.5 -b -n2 | awk '/Cpu\(s\)/ {result=$2+$4} END {printf "%3.0f\n",result'}` – Jotne Sep 15 '14 at 08:40

2 Answers2

1

Either escape the " quotes inside your command string, i.e., replace them with \" or quote the command string with triple quotes `'''.

Using Jotne's version

cmd = '''top -d 0.5 -b -n2 | awk '/Cpu\(s\)/ {result=$2+$4} END {printf "%3.0f\n",result'}'''
PM 2Ring
  • 54,345
  • 6
  • 82
  • 182
0

In my opinion and as you suggested you may try other solutions, there already exists some tools which will fit your needs. For instance the psutil library.

Here is a very simple example which I think does what you want:

import psutil
print psutil.cpu_percent(interval=1)

If you still want to use your solution, you should read the python subprocess documentations about how to replace shell pipelines, and/or the existing stackoverflow topics about that (for instance this one)

Community
  • 1
  • 1
Emilien
  • 2,385
  • 16
  • 24