473,734 Members | 2,693 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 3556
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
14359
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. Now, I assume I can make cmd.exe run foo.py by asociating *.py with the python interpreter.
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. This seems to be a requirement for the Process class. All I have is a string (which is the command...
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...
7
66686
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
2985
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
3945
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 learn the bash 'language', then I won't just yet. Thanks.
4
2379
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 command-line scripts (which is optparser-based now) and have some ideas how to proceed. But probably...
1
4006
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
6729
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 "cmd /c sample.bat"
0
8946
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
8776
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,...
0
9310
jinu1996
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...
1
9236
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 most users, this new feature is actually very convenient. If you want to control the update process,...
0
8186
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...
0
6031
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
4550
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...
1
3261
by: 6302768590 | last post by:
Hai team i want code for transfer the data from one system to another through IP address by using C# our system has to for every 5mins then we have to update the data what the data is updated we have to send another system
3
2180
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.