473,836 Members | 2,130 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

how to get the stdout of the script that os.system executes

5 New Member
i know that in python, os.system(cmd) can be used to execute a script or command, and the return value is 0 if successful, rather than the standard output of the script that it executes.


>>> a=os.system("ec ho hello")
>>> a
0 (rather than "hello")

my question is how to direct the standard output into a variable in my python script.
Oct 31 '07
11 45271
511 Recognized Expert Contributor
note also that commands modules is Unix specific.( AFAIK , correct me if i am wrong)
i use this sometimes
Expand|Select|Wrap|Line Numbers
  1. import os
  2. fin, fout = os.popen4(cmd)
  3. print fout.read() #standard out
Nov 2 '07 #11
126 New Member
note also that commands modules is Unix specific.( AFAIK , correct me if i am wrong)
i use this sometimes
Expand|Select|Wrap|Line Numbers
  1. import os
  2. fin, fout = os.popen4(cmd)
  3. print fout.read() #standard out

commands is a simple unix specific wrapper for os.popen:
The whole content of commands.py:

Expand|Select|Wrap|Line Numbers
  1. smygis@Bob:~$ cat /usr/lib/python2.5/commands.py
  2. """Execute shell commands via os.popen() and return status, output.
  4. Interface summary:
  6.        import commands
  8.        outtext = commands.getoutput(cmd)
  9.        (exitstatus, outtext) = commands.getstatusoutput(cmd)
  10.        outtext = commands.getstatus(file)  # returns output of "ls -ld file"
  12. A trailing newline is removed from the output string.
  14. Encapsulates the basic operation:
  16.       pipe = os.popen('{ ' + cmd + '; } 2>&1', 'r')
  17.       text = pipe.read()
  18.       sts = pipe.close()
  20.  [Note:  it would be nice to add functions to interpret the exit status.]
  21. """
  23. __all__ = ["getstatusoutput","getoutput","getstatus"]
  25. # Module 'commands'
  26. #
  27. # Various tools for executing commands and looking at their output and status.
  28. #
  29. # NB This only works (and is only relevant) for UNIX.
  32. # Get 'ls -l' status for an object into a string
  33. #
  34. def getstatus(file):
  35.     """Return output of "ls -ld <file>" in a string."""
  36.     return getoutput('ls -ld' + mkarg(file))
  39. # Get the output from a shell command into a string.
  40. # The exit status is ignored; a trailing newline is stripped.
  41. # Assume the command will work with '{ ... ; } 2>&1' around it..
  42. #
  43. def getoutput(cmd):
  44.     """Return output (stdout or stderr) of executing cmd in a shell."""
  45.     return getstatusoutput(cmd)[1]
  48. # Ditto but preserving the exit status.
  49. # Returns a pair (sts, output)
  50. #
  51. def getstatusoutput(cmd):
  52.     """Return (status, output) of executing cmd in a shell."""
  53.     import os
  54.     pipe = os.popen('{ ' + cmd + '; } 2>&1', 'r')
  55.     text = pipe.read()
  56.     sts = pipe.close()
  57.     if sts is None: sts = 0
  58.     if text[-1:] == '\n': text = text[:-1]
  59.     return sts, text
  62. # Make command argument from directory and pathname (prefix space, add quotes).
  63. #
  64. def mk2arg(head, x):
  65.     import os
  66.     return mkarg(os.path.join(head, x))
  69. # Make a shell command argument from a string.
  70. # Return a string beginning with a space followed by a shell-quoted
  71. # version of the argument.
  72. # Two strategies: enclose in single quotes if it contains none;
  73. # otherwise, enclose in double quotes and prefix quotable characters
  74. # with backslash.
  75. #
  76. def mkarg(x):
  77.     if '\'' not in x:
  78.         return ' \'' + x + '\''
  79.     s = ' "'
  80.     for c in x:
  81.         if c in '\\$"`':
  82.             s = s + '\\'
  83.         s = s + c
  84.     s = s + '"'
  85.     return s
Nov 2 '07 #12

Sign in to post your reply or Sign up for a free account.

Similar topics

by: Sticks | last post by:
ok... im not quite sure how to describe my problem. i have a php script that runs through my entire php site and writes the resulting output to html files. this is necessary as the nature of the hosting available to me for this particular page prohibits me from using php/mysql as i would like. my script works simply by using output buffers and an include the relevant section of code is as follows: ob_start();
by: Ben Floyd | last post by:
It goes like this: Im converting a perl script that executes a command on each result of a directory listing. In perl, all is well. In Python, using approximately the same logic creates a seemingly random problem I can't pin down. I hesitated to ask this question since it's so Slackware Linux-centric, and im new to Python. It's hard to ask in a generic way, but im out of options...
by: Paul Nilsson | last post by:
Hi, Does anyone know how to redirect text output when issuing a system or an execlp call? I have a GUI that insists on opening up a console whenever I give a system function call, and I would like to redirect the text output to a char buffer instead. Paul
by: alexLIGO | last post by:
Hi, I am trying to run a python script that executes several other programs on the bash (under linux) and reads some of the output of those programs. This works fine for a couple of os.system() calls, but then it does not work anymore. os.system() returns always -1, but when executing exactly the same program directly on the linux-bash it works! Could this be a memory problem? It happens when there is much data stored in a python...
by: Russ | last post by:
I've been trying to get my head around this for 3 days now and it seems like everything I try does not work for one reason or another. I built a test page using the TabStrip and MultiPage controls. The example shows how to put up pictures in each tab, and it works fine. But of course I don't want pictures, I want a webform where the data is different in each tab/view. The form could be different in each tab too, but for now I'll settle...
by: Elad | last post by:
Hello All, I am trying to capture some printf's from a C function called by python. <Working under winxp> I have tried to following: STDOUT = 1 # stdout fd (re, we) = os.pipe() # Create re / write handlers
by: tatamata | last post by:
Hello. How can I run some Python script within C# program? Thanks, Zlatko
by: grikdog | last post by:
How to I capture stdout output from a system call and pipe it back into my running script? system "echo foobar"; # how to continue here with "foobar" in stdin ?? ... I can fake it with pipes and additional scripts, but that seems like overkill.
by: vivek samantray | last post by:
i have a script which executes several queries for n number of records.How can is set the time in that to know how much time each query took to run
by: marktang | last post by:
ONU (Optical Network Unit) is one of the key components for providing high-speed Internet services. Its primary function is to act as an endpoint device located at the user's premises. However, people are often confused as to whether an ONU can Work As a Router. In this blog post, we’ll explore What is ONU, What Is Router, ONU & Router’s main usage, and What is the difference between ONU and Router. Let’s take a closer look ! Part I. Meaning of...
by: Hystou | last post by:
Most computers default to English, but sometimes we require a different language, especially when relocating. Forgot to request a specific language before your computer shipped? No problem! You can effortlessly switch the default language on Windows 10 without reinstalling. I'll walk you through it. First, let's disable language synchronization. With a Microsoft account, language settings sync across devices. To prevent any complications,...
by: Oralloy | last post by:
Hello folks, I am unable to find appropriate documentation on the type promotion of bit-fields when using the generalised comparison operator "<=>". The problem is that using the GNU compilers, it seems that the internal comparison operator "<=>" tries to promote arguments from unsigned to signed. This is as boiled down as I can make it. Here is my compilation command: g++-12 -std=c++20 -Wnarrowing bit_field.cpp Here is the code in...
by: jinu1996 | last post by:
In today's digital age, having a compelling online presence is paramount for businesses aiming to thrive in a competitive landscape. At the heart of this digital strategy lies an intricately woven tapestry of website design and digital marketing. It's not merely about having a website; it's about crafting an immersive digital experience that captivates audiences and drives business growth. The Art of Business Website Design Your website is...
by: tracyyun | last post by:
Dear forum friends, With the development of smart home technology, a variety of wireless communication protocols have appeared on the market, such as Zigbee, Z-Wave, Wi-Fi, Bluetooth, etc. Each protocol has its own unique characteristics and advantages, but as a user who is planning to build a smart home system, I am a bit confused by the choice of these technologies. I'm particularly interested in Zigbee because I've heard it does some...
by: agi2029 | last post by:
Let's talk about the concept of autonomous AI software engineers and no-code agents. These AIs are designed to manage the entire lifecycle of a software development project—planning, coding, testing, and deployment—without human intervention. Imagine an AI that can take a project description, break it down, write the code, debug it, and then launch it, all on its own.... Now, this would greatly impact the work of software developers. The idea...
by: conductexam | last post by:
I have .net C# application in which I am extracting data from word file and save it in database particularly. To store word all data as it is I am converting the whole word file firstly in HTML and then checking html paragraph one by one. At the time of converting from word file to html my equations which are in the word document file was convert into image. Globals.ThisAddIn.Application.ActiveDocument.Select();...
by: adsilva | last post by:
A Windows Forms form does not have the event Unload, like VB6. What one acts like?
by: muto222 | last post by:
How can i add a mobile payment intergratation into php mysql website.

By using Bytes.com and it's services, you agree to our Privacy Policy and Terms of Use.

To disable or enable advertisements and analytics tracking please visit the manage ads & tracking page.