0

Hi i have this issue i am executing a shell command in my python script and the probleme i am getting two results instead of 1. The first is the id that i want to store the second is a 0 and i guess its the result code.

This is my code

import os
cmd = "/path/to/ctl so list | tail -1 | awk '{print $1}'" 
event_id = os.system(cmd) 
print(event_id) 

and this is the result:

225
0

how can i delete that 0.

Thanks

  • The quick answer is: don't print it; you've saved the return code of os.system() into event_id; that is 0. The output of the command you ran showed up as well. Did you intend to capture the output of the command into event_id? – Jeff Schaller Jul 23 '19 at 15:56
  • i just want to retrieve the output without the return code – Akdim Karim Jul 23 '19 at 16:01
2

Your guess is correct that 0 is the return code from your shell command. os.system(cmd) is executing your command and outputting the result, and then the return code is stored in event_id and printed.

You should use the subprocess module instead.

import subprocess
cmd = "/path/to/ctl so list | tail -1 | awk '{print $1}'" 
event_id = subprocess.check_output(cmd, shell=True).rstrip()
print(event_id)
  • the command is working but I am receiving value along with empty line – Akdim Karim Jul 23 '19 at 16:10
  • @AkdimKarim, See my edit. Appending rstrip() to event_id in the print command will strip all trailing whitespace. – Peschke Jul 23 '19 at 16:13

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.