-1

I'm trying to do a for loop with popen which uses the variable .How to use the "line" variable inside the for loop which uses os.open for linux commands.

os.popen("yum history | awk '{print $1}' | grep -v 'Loaded\|history\|ID\|-' > ids.txt" ).read()
myfile = open("ids.txt", "r")
for line in myfile:
     first=os.popen("yum history info + line + | grep -i Command | awk '{print $4,$5}'").read().strip()
#     first="yum history info +line | grep -i Command "
     print(line)
     print(first)
myfile.close()
wovano
  • 4,543
  • 5
  • 22
  • 49
Hema
  • 11
  • 2
  • what's the issue you've run into? – Mahrkeenerh Oct 07 '21 at 10:56
  • 1
    The term you are looking for is "string concatenation" - typing that into a search engine of your choice will give lots of results, e.g.: https://www.pythonforbeginners.com/concatenation/string-concatenation-and-formatting-in-python – UnholySheep Oct 07 '21 at 10:56
  • 1
    As a new user here, please also take the [tour] and read [ask]. Also, when applying tags to questions, read their description. Welcome to SO though! – Ulrich Eckhardt Oct 07 '21 at 11:04
  • The right way to do this would be to use the [`subprocess`](https://docs.python.org/3/library/subprocess.html) module. – Peter Wood Oct 07 '21 at 11:04
  • The [`grep is useless`](https://www.iki.fi/era/unix/award.html#grep) but more fundamentally, both `grep` and `awk` can be trivially replaced with native Python constructs. – tripleee Oct 07 '21 at 11:55
  • 1
    There is no way `popen` can return anything in `read()` when you redirect output to a file. – tripleee Oct 07 '21 at 11:56

1 Answers1

-1
os.popen("yum history | awk '{print $1}' | grep -v 'Loaded\|history\|ID\|-' > ids.txt" ).read()
myfile = open("ids.txt", "r")
for line in myfile:
     first=os.popen("yum history info " + line + "| grep -i Command | awk '{print $4,$5}'").read().strip()
#     first="yum history info +line | grep -i Command "
     print(line)
     print(first)
myfile.close()

with f string:

os.popen("yum history | awk '{print $1}' | grep -v 'Loaded\|history\|ID\|-' > ids.txt" ).read()
myfile = open("ids.txt", "r")
for line in myfile:
     first=os.popen(f"yum history info {line} | grep -i Command | awk '{{print $4,$5}}'").read().strip()
#     first="yum history info +line | grep -i Command "
     print(line)
     print(first)
myfile.close()
Bhagyesh Dudhediya
  • 1,800
  • 1
  • 13
  • 16
  • Im trying to call the line variable from for loop and use it in the below command os.popen("yum history info " line "| grep -i Command | awk '{print $4,$5}'") – Hema Oct 07 '21 at 11:11
  • It is throwing syntax error Bhagyesh – Hema Oct 07 '21 at 13:49