0

I want to run a python script that can execute OS (linux) commands , I got few modules that helps me in doing that like os, subprocess . In OS module am not able to redirect the output to a variable . In subprocess.popen am not able to use variable in the arguments. Need someone help in finding the alternative .

Am trying to run some OS commands from python script . for example df -h output. It works fine with by using some modules like os or subprocess .But am not able to store those output to any variable .

Here am not able to save this output to a variable . How do I save this to a variable.

i saw multiple other options like subprocess.Popen but am not getting proper output.

Below program i used subprocess module but here I have another issue , as the command is big am not able to use variables in subprocess.Popen.

  • shantojosee@srv-dcb-erp-mgnt01:~/python> cat ping #!/usr/bin/python import subprocess # Ask the user for input host = raw_input("Enter a host to ping: ") # Set up the echo command and direct the output to a pipe p1 = subprocess.Popen(['ping', '-c 2', host], stdout=subprocess.PIPE) # Run the command output = p1.communicate()[0] print output shantojosee@srv-dcb-erp-mgnt01:~/python> – Shanto Jose Jul 25 '16 at 14:00
  • 1
    Please [edit] your question to add code, not the comments section – DeepSpace Jul 25 '16 at 14:00

2 Answers2

0

You can use the subprocess method check_output

import subprocess
output = subprocess.check_output("your command", shell=True)

see previously answered SO question here for more info: https://stackoverflow.com/a/8659333/3264217

Also for more info on check_output, see python docs here: https://docs.python.org/3/library/subprocess.html#subprocess.check_output

Community
  • 1
  • 1
Mattew Whitt
  • 2,194
  • 1
  • 15
  • 19
0

Use either subprocess or pexpect depending on what is your exact use case.

subprocess can do what os.system does and much more. If you need to start some command, wait for it to exit and then get the output, subprocess can do it:

import subprocess
res = subprocess.check_output('ls -l')

But if you need to interact with some command line utility, that is repeatedly read/write, then have a look at pexpect module. It is written for Unix systems but if you ever want to go cross-platform, there is a port for Windows called winpexpect.

spawn's attribute 'before' is probably what you need:

p = pexpect.spawn('/bin/ls')
p.expect(pexpect.EOF)
print p.before

(see the docs)

kstera
  • 11
  • 2