0

I'm trying to write a Python script that reads lines of strings from a file and executes a bash-shell command with each line as parameter:

#!/usr/bin/env python
# -*- coding: utf-8 -*-
import os

lines = [line.strip() for line in open('/tmp/i586rpm.txt')]
for rpm in lines:
    try:
        s = os.system("rpm -qip") % lines

    except Exception:
        print "Something wrong"

But I always get an error. I think that there is something wrong with % lines.

Any ideas?

0

3 Answers 3

6

Yes, you're not building the command string properly. Try:

s = os.system("rpm -qip \"%s\"" % rpm)
Sign up to request clarification or add additional context in comments.

Comments

4

There are a few things that could be improved:

  • Uses os.system instead of subprocess.Popen (for more information, please have look at the documentation)
  • Iterates over lines, but it doesn't use the iteration variable (rpm)
  • Attemps to format the output string from os.system with lines as a parameter.

My advice is to use this code:

for line in lines:
    p = subprocess.Popen('rpm -qip {0}'.format(line),
                         shell=True,
                         stdout=subprocess.PIPE)
    stdout, stderr = p.communicate()

4 Comments

This answer is by far better than unwind's.
Great.But how i can output rpm -qip {0} into directly into shell or file?
@user413036 I'm not sure what do you mean. If the problem is regarding {0}, note that '{0}'.format(line) is equivalent to '%s' % line.
@user413036 You probably don't want to output it into a shell, you just wand to execute it. And that's what the call above for. Maybe even better p = subprocess.Popen(['rpm', '-qip', '{0}'.format(line)], stdout=subprocess.PIPE) - the shell is not needed here.
-1

instead of

for rpm in lines:
    s = os.system("rpm -qip") % lines

do this

for rpm in lines:
    s = os.system('rpm -qip "%s"' % rpm) 

EDIT correct the code

1 Comment

That still won't work as you put the % rpm outside of the os.system call. s = os.system('rpm -qip "%s"' % rpm)

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.