473,807 Members | 2,853 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

Wrapping A Shell

I'm not sure if this is really the right place to ask this question, but
since the implementation is in Python, I figured I'd give it a shot.

I want to "wrap" a shell process using popen inside of python program
rather than creating a new shell process for each line I process in the
app. For example, the code might look like:
std = stdin, stdout, stderr = os.popen3("bash ")

print >stdin, "ls"

print stdout.readline ()

However, it appears my understanding of popen (or perhaps buffered IO)
is off somewhere, because this certainly doesn't work anything like I
expect it to (it hangs on stdout.readline ).

Obviously the example above is very contrived, but eventually I'll be
using this in an OpenGL "terminal" widget. Am I approaching this the
wrong way?

Nov 28 '06 #1
2 3981

Jeremy Moles wrote:
I'm not sure if this is really the right place to ask this question, but
since the implementation is in Python, I figured I'd give it a shot.

I want to "wrap" a shell process using popen inside of python program
rather than creating a new shell process for each line I process in the
app. For example, the code might look like:
std = stdin, stdout, stderr = os.popen3("bash ")

print >stdin, "ls"

print stdout.readline ()

However, it appears my understanding of popen (or perhaps buffered IO)
is off somewhere, because this certainly doesn't work anything like I
expect it to (it hangs on stdout.readline ).

Obviously the example above is very contrived, but eventually I'll be
using this in an OpenGL "terminal" widget. Am I approaching this the
wrong way?
Try flushing the bufffer for stdin.
Cheers,
-T

Nov 28 '06 #2
Jeremy Moles <je****@emperor linux.comwrote:
I'm not sure if this is really the right place to ask this question, but
since the implementation is in Python, I figured I'd give it a shot.

I want to "wrap" a shell process using popen inside of python program
rather than creating a new shell process for each line I process in the
app. For example, the code might look like:
std = stdin, stdout, stderr = os.popen3("bash ")

print >stdin, "ls"

print stdout.readline ()

However, it appears my understanding of popen (or perhaps buffered IO)
is off somewhere, because this certainly doesn't work anything like I
expect it to (it hangs on stdout.readline ).

Obviously the example above is very contrived, but eventually I'll be
using this in an OpenGL "terminal" widget. Am I approaching this the
wrong way?
Short answer: use pexpect

http://pexpect.sourceforge.net/

Long answer:

Firstly modern pythonistas use subprocess instead of os.popen*.

Secondly, buffering is going to cause you trouble and possible
deadlocks.

There are two ways to rid yourself of deadlock.

1) read and write from seperate threads / processes. This is the
traditional unix way

2) use non blocking IO

Here is a possible way to solve the problems with subprocess (unix
only) and non blocking IO.

However I suspect you really want to use pexpect for this job...

from os import O_NONBLOCK
from errno import EAGAIN
from subprocess import Popen, PIPE
from fcntl import fcntl, F_SETFL, F_GETFL
from time import time

p = Popen(["/bin/bash", "-i"], shell=False, bufsize=0, stdin=PIPE, stdout=PIPE, stderr=PIPE, close_fds=True)

# Make output streams non blocking (unix only)
for fd in (p.stdout.filen o(), p.stderr.fileno ()):
fcntl(fd, F_SETFL, fcntl(fd, F_GETFL) | O_NONBLOCK)

def read_output(p, timeout=1.0):
"""Read the output from the subprocess, with timeout"""
end_time = time() + timeout
output = ""
while time() < end_time:
try:
output += p.stdout.read(1 024)
except IOError, e:
if e.errno != EAGAIN:
raise
return output

p.stdin.write(" ls\n")
print read_output(p)
p.stdin.write(" uname -a\n")
print read_output(p)

--
Nick Craig-Wood <ni**@craig-wood.com-- http://www.craig-wood.com/nick
Nov 29 '06 #3

This thread has been closed and replies have been disabled. Please start a new discussion.

Similar topics

13
3866
by: Roy Smith | last post by:
I've got a C library with about 50 calls in it that I want to wrap in Python. I know I could use some tool like SWIG, but that will give me a too-literal translation; I want to make some modifications along the way to make the interface more Pythonic. For example, all of these functions return an error code (typically just errno passed along, but not always). They all accept as one of their arguments a pointer to someplace to store...
11
5612
by: yawnmoth | last post by:
word wrapping normally treats some spaces as line feeds, if there hasn't been a line feed for quite a while. so while a string with eighty consecutive a's might not word wrap, a space placed squarely in the middle of that string will sorta word wrap. so why doesn't it seem to work with !'s? here's a page that demonstrates how !'s don't seem to word wrap: http://www.geocities.com/terra1024/wordwrap.htm here's a page that shows how...
8
1333
by: Siemel Naran | last post by:
Hi. I'm writing a command shell that reads commands from standard input. At this point I have the command in a std::string. Now I want to execute this command in the shell. From the Borland newsgroups I learned that there is a function in stdlib.h called system. int system(const char *command); First question, is the system command ANSI compliant. Because I include <cstdlib> and write std::system(command.c_str()); it looks like an...
5
5301
by: nimdez | last post by:
Hi, I am working on an existing code base in which a lot of data displayed to the user is formatted in tables. Most tables are printed row-by-row using printf() with "%s" print conversion specification for each column (e.g. printf(%10s %25s %15s\n", pszCol1, pszCol2, pszCol3)). My problem is that when a string is longer the column's width, it overflows the column and takes the table out of alignment. What I want it to do is word-wrap...
7
1172
by: S Borg | last post by:
Hello, I am parsing text from one document to another. I have a scheme similar to: for x in myfoobar: print >> mytextfile, "%s " % mydictionary, #all on same line print >> mytextfile, '\n' #new line
8
13876
by: Nathan | last post by:
I am trying to prevent a horizontal list from wrapping. Each list item is floated with "float: left". Currently I use an ugly hack. I set the width of the list to a large number which is guananteed greater than the total width of all items. Is there a way to accomplish this without my hack? It would be handy because I would like to read the total width of all items in javascript. I looked into white-space: nowrap, but it doesn't work...
3
1952
by: Rocky Zhou | last post by:
I wonder is there any way to make the wrapper program can wrap options && arguments for the the subprocess/command the wrapper will execute? by getopt or optparse module? This is something like the shell script like this: optwrap="" while ; do case $1 in -a) do-something; shift ;;
21
3042
by: Tom Gur | last post by:
Hi, It's seems that csh and tcsh acts a bit different when handling special characters in quotes. i.e: if i'll supply my program with the following arguments: -winpath "c:\\temp\\" tcsh will take it as -winpath "c:\temp\" and csh will take it literally (with the double-slashes). Is there a way for me to know what shell is currently running my
25
62580
by: dennijr | last post by:
ok, shell always used to be easy for me, now its starting to get annoying cause i dont know wats wrong heres the simplist code possible: Private Sub IExplorer_Click() a = Shell("C:\Program Files\Internet Explorer\Iexplore.exe http://www.google.ca", vbMaximizedFocus) End Sub i have a program thats been on my desktop for about a month now that uses these 3 lines of code(supposed to be 3 lines but it doesnt quite fit) and its been...
0
9720
marktang
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...
0
10626
Oralloy
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...
0
10112
tracyyun
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...
0
9193
agi2029
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...
1
7650
isladogs
by: isladogs | last post by:
The next Access Europe User Group meeting will be on Wednesday 1 May 2024 starting at 18:00 UK time (6PM UTC+1) and finishing by 19:30 (7.30PM). In this session, we are pleased to welcome a new presenter, Adolph Dupré who will be discussing some powerful techniques for using class modules. He will explain when you may want to use classes instead of User Defined Types (UDT). For example, to manage the data in unbound forms. Adolph will...
0
6879
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();...
0
5546
by: TSSRALBI | last post by:
Hello I'm a network technician in training and I need your help. I am currently learning how to create and manage the different types of VPNs and I have a question about LAN-to-LAN VPNs. The last exercise I practiced was to create a LAN-to-LAN VPN between two Pfsense firewalls, by using IPSEC protocols. I succeeded, with both firewalls in the same network. But I'm wondering if it's possible to do the same thing, with 2 Pfsense firewalls...
0
5685
by: adsilva | last post by:
A Windows Forms form does not have the event Unload, like VB6. What one acts like?
3
3011
bsmnconsultancy
by: bsmnconsultancy | last post by:
In today's digital era, a well-designed website is crucial for businesses looking to succeed. Whether you're a small business owner or a large corporation in Toronto, having a strong online presence can significantly impact your brand's success. BSMN Consultancy, a leader in Website Development in Toronto offers valuable insights into creating effective websites that not only look great but also perform exceptionally well. In this comprehensive...

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.