-3

I need to execute a shell command in python and need to store the result to a variable. How can I perform this. I need to execute openssl rsautl -encrypt -inkey key and get the result to a variable.

---edit---

How can I execute

perl -e 'print "hello world"' | openssl rsautl -encrypt -inkey key

in python and get the output..

javaDeveloper
  • 1,403
  • 3
  • 28
  • 42
  • 5
    Could you search before ask? There's tons of similar questions on SO. – laike9m May 18 '15 at 11:43
  • possible duplicate of [Calling an external command in Python](http://stackoverflow.com/questions/89228/calling-an-external-command-in-python) – Glorfindel May 18 '15 at 11:48

2 Answers2

3

You can use subprocess.check_output

from subprocess import check_output

out = check_output(["openssl", "rsautl", "-encrypt", "-inkey", "key"])

The output will be stored in out.

Padraic Cunningham
  • 176,452
  • 29
  • 245
  • 321
  • 1
    @RakeshNair, http://stackoverflow.com/a/29085292/2141635 http://stackoverflow.com/questions/28154437/using-subprocess-to-get-output-of-grep-piped-through-head-1/28154788#28154788 – Padraic Cunningham May 18 '15 at 13:00
1

A Simple way to execute a shell command is os.popen:

import os

cmdOutput1 = os.popen("openssl rsautl -encrypt -inkey key").readlines()
cmdOutput2 = os.popen("perl -e 'print \"hello world\"' | openssl rsautl -encrypt -inkey key").readlines()

All it takes is the command you want to run in the form of one String. It will return you an open file object. By using .readlines() this open file object will be converted to a list, where an Item in the List will correspond to a single line of Output from your command.

cptPH
  • 2,401
  • 1
  • 29
  • 35
  • While this post may answer the question, it is still a good idea to add some explanation and, possibly, some links to the relevant documentation. Answers with good explanations and references are usually more useful both to the current OP and to the future visitors. Full detailed answers are also more likely to attract positive votes. – Eugene Podskal May 18 '15 at 12:26
  • I honestly thought the command itself is pretty self explanatory, but you are right I still should have explained it a bit -> I've updated my answer accordingly. – cptPH May 18 '15 at 13:07
  • I never said that it wasn't self-explanatory. Just that block of code on its own has less chances to be accepted and(or) upvoted. Good answers usually explain why OP's code failed, what can be done to rectify it, and, perhaps, some additional related recommendations. – Eugene Podskal May 18 '15 at 13:17
  • 1
    It's not like Python cannot `write("Hello world")` without the help of Perl. – tripleee May 18 '15 at 13:34
  • I'm not questioning the commands he wants to run, I just show how it can be done ;-) – cptPH May 18 '15 at 13:41