0

I am invoking shell script using os.execvp() in python. my shell script has some echo statements whcih I want to redirect in file.

Here is what I am trying:

cmd = "/opt/rpm/rpm_upgrade.sh >& /opt/rpm/upgrader.log"
cmdline = ["/bin/sh", cmd]
os.execvp(cmdline[0], cmdline)

Below is the error I am getting:

Error:   /bin/sh: /opt/rpm/rpm_upgrade.sh >& /opt/rpm/upgrader.log: No such file or directory

Can any one help?

3
  • Is /opt/Druva/rpm/rpm_upgrade.sh and /opt/rpm/ exist? Commented Apr 27, 2016 at 10:21
  • No such file or directory - I wonder what could that possibly mean?... Commented Apr 27, 2016 at 10:22
  • @alpert: Yes. The rpm_upgrade.sh file is exist. That means /opt/rpm/ directory is also exist. Commented Apr 27, 2016 at 10:35

1 Answer 1

1

This is happening because you are passing this entire string as if it were the program name to execute:

"/opt/rpm/rpm_upgrade.sh >& /opt/rpm/upgrader.log"

The easy way to fix this is:

cmdline = ["/bin/sh", "/opt/rpm/rpm_upgrade.sh",
           ">&", "/opt/rpm/upgrader.log"]
os.execvp(cmdline[0], cmdline)

Now sh will receive three arguments rather than one.

Or you can switch to the more full-featured subprocess module, which lets you redirect output in Python:

import subprocess
with open("/opt/rpm/upgrader.log", "wb") as outfile:
    subprocess.check_call(["/opt/rpm/rpm_upgrade.sh"], shell=True,
                          stdout=outfile, stderr=subprocess.STDOUT)
Sign up to request clarification or add additional context in comments.

3 Comments

It is fixing above error but problem is This fix is not redirecting my rpm_upgrade.sh 's echo statements to /opt/rpm/upgrader.log file. It is still printing on console.
@AmarPatil: I've added perhaps a better code snippet to try to solve that problem.
When I use code "process = Popen("rpm -Uvh /opt/rpm/new/client-4.1-5470.x86_64.rpm", stdout=PIPE, shell=True) process.communicate() " Its hangs for long time. Anyone help me here ?

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.