473,573 Members | 4,147 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

How to use only a sub shell to execute many commands in python

Please see the following code.
Suppose I have many shell commands to be executed. And I don't want to
fork a sub shell for each command(eg: status,output =
commands.getsta tusoutput(cmd)) because it is too expensive. I want to
use only one sub shell to execute all these commands and want to get
each command's output. How can I accomplish this task ? Thanks in
advance.

=============== =============== =============
#!/usr/bin/env python
import os
fi, fo = os.popen2(
'''
while read line
do
eval $line
done
''', 't')

#Suppose I have many commands to execute, but I don't want to fork a
sub shell for each command
cmds = ['date','uptime' ,'pwd','ls -rltF','who']

for cmd in cmds:
#pseudocode
fi.executeCmd(c md)
output = fo.readResult()

print output
=============== =============== =============
Jan 18 '08 #1
1 3546
En Fri, 18 Jan 2008 09:31:25 -0200, raocheng <rc******@gmail .comescribi�:
Please see the following code.
Suppose I have many shell commands to be executed. And I don't want to
fork a sub shell for each command(eg: status,output =
commands.getsta tusoutput(cmd)) because it is too expensive. I want to
use only one sub shell to execute all these commands and want to get
each command's output. How can I accomplish this task ? Thanks in
advance.
The hard part is to determine WHEN the command has completed its
execution, because there is no indication of that. One way would be to set
a relatively uncommon prompt, and look for that string in stdout. You
can't read beyond that, else the code would block.
Another way is to use a separate thread to read from stdout/stderr, and
set a timeout; when no more output comes whithin the timeout, you assume
the command has finished.

The code below uses the first approach, changing the prompt to <$$$>\r\n.
I've tested it on Windows only, but should work on Linux too with some
minor modifications.

import subprocess
from os import getenv

# Windows only, this is to determine the shell in use
# Linux users may try with getenv("SHELL", "sh")
shell = getenv("COMSPEC ", "cmd")
p = subprocess.Pope n(shell, stdin=subproces s.PIPE,
stdout=subproce ss.PIPE,
stderr=subproce ss.STDOUT)

expected = '<$$$>\r\n'
cmds = ['prompt $L$$$$$$$G$_',' date /t','cd','dir',' ipconfig /all']
# The first command above sets an uncommon prompt, ending with a newline.
# On Linux use PS1=whatever, but make sure it ends in \n and set the
# expected variable accordingly.

for cmd in cmds:
print ">>>",cmd
p.stdin.write(' %s\n' % cmd)
while True:
line = p.stdout.readli ne()
if line.endswith(e xpected): break
print line,

print "Waiting for subshell to terminate"
p.stdin.write(" exit\n")
p.wait()
print "Done"
--
Gabriel Genellina

Jan 18 '08 #2

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

Similar topics

2
14347
by: Jorgen Grahn | last post by:
I couldn't think of a good solution, and it's hard to Google for... I write python command-line programs under Win2k, and I use the bash shell from Cygwin. I cannot use Cygwin's python package because of a binary module which has to be compiled with Visual C 6. My scripts start with a '#!/usr/bin/env python' shebang, as God intended. ...
1
536
by: Mike Kamzyuk | last post by:
Hello all. This topic has been covered on google groups before, but I couldn't find a good response. I have a shell command I wish to execute from c# (or vb or your favorite .net language). I know the relevant class is System.Diagnostics.Process. The problem is that I don't know the name of the exe (or bat, or whatever) of the process. ...
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...
7
66681
by: fileexit | last post by:
How can I execute shell commands from within python. Specifically, I am looking for something like the shell "cat". But this also made me wonder how to execute shell commands anyway, just if i needed to do that in the future.
7
2977
by: spec | last post by:
Hi all, I know nothing about Python. What I need to do is to get a Python script to execute a local shell script. I do not need any output. What would be th eeasiest way to accomplish this? Thanks!
16
3930
by: John Salerno | last post by:
Hi all. I just installed Ubuntu and I'm learning how to use the bash shell. Aside from the normal commands you can use, I was wondering if it's possible to use Python from the terminal instead of the normal bash commands (e.g. print instead of echo). My main reason for asking is that I like using Python for everything, and if I don't need to...
4
2367
by: Anastasios Hatzis | last post by:
I'm looking for a pattern where different client implementations can use the same commands of some fictive tool ("foo") by accessing some kind of API. Actually I have the need for such pattern for my own tool (http://openswarm.sourceforge.net). I already started restructuring my code to separate the actual command implementations from the...
1
4004
by: Riccardo Maria Bianchi | last post by:
Hello! :) I'm trying to run shell commands both with os.system() and subprocess.Popen() class. But I can't run aliases or function defined in my .bashrc file, like in the login interactive shell. Can you help me? Maybe have I to add some commands to load the .bashrc?
3
6725
by: Max Vit | last post by:
I have come across a strange issue whilst trying to use a shell command call from Access and have spent some time trying to figure this out but can't find the cause as yet. The issue is: I need to execute a command call from within Access to execute a batch file (sample.bat). To do this, we use the Shell function, something like: Shell...
0
7789
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...
0
7707
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...
1
7800
by: Hystou | last post by:
Overview: Windows 11 and 10 have less user interface control over operating system update behaviour than previous versions of Windows. In Windows 11 and 10, there is no way to turn off the Windows Update option using the Control Panel or Settings app; it automatically checks for updates and installs any it finds, whether you like it or not. For...
0
8086
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...
0
6432
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...
1
5605
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...
0
5296
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...
0
3737
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...
1
1325
muto222
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.