473,772 Members | 2,244 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

outputting a command to the terminal?

Here's my new project: I want to write a little script that I can type
at the terminal like this:

$ scriptname package1 [package2, ...]

where scriptname is my module name and any subsequent arguments are the
names of Linux packages to install. Running the script as above will
create this line:

sudo aptitude install package1 package2 ...

It will run that line at the terminal so the package(s) will be installed.

Now, the extra functionality I want to add (otherwise I would just
install them normally!) is to save the package names to a text file so I
can now the names of programs I've manually installed, if I ever want to
check the list or remove packages.

So creating the proper bash command (sudo aptitude install ...) is easy,
and writing the names to a file is easy. But I have two questions:

1. First of all, does Linux keep track of the packages you manually
install? If so, then I won't have to do this at all.

2. Assuming I write this, how do output the bash command to the
terminal? Is there a particular module that Python uses to interact with
the terminal window that I can use to send the install command to the
terminal?

Thanks.
Aug 13 '06
16 2721
Dennis Lee Bieber wrote:
Well, I don't do shell scripts either, but... looking at the
sample... "$@" is likely the shell equivalent of Python's sys.argv -- or
*sys.argv if passed down
Yeah, kinda equivalent to *sys.argv[1:].
Aug 14 '06 #11
Steven Bethard wrote:
P.S. Thank *you* for posting this. As a result, I've been convinced
that argparse should grow a 'outfile' type, something I've been debating
with myself about for a while now.
Heh heh. I'm glad my ignorance can inspire those around me. ;)
Aug 14 '06 #12
Yu-Xi Lim wrote:
Steven Bethard wrote:
>import argparse # http://argparse.python-hosting.com/
import subprocess
import sys

Why not the standard lib's optparse?
The page referenced above gives a variety of reasons, but the two most
important things in this example are: argparse supports parsing of both
positional and optional arguments, and argparse generates better usage
messages.

Since argparse supports positional arguments, I can write something like::

parser.add_argu ment('packages' , ..., nargs='+', ...)

and then the arparse module will enforce that at least one positional
argument was given. With optparse, you'd do something like:

options, args = parser.parse_ar gs()
if not args:
parser.error('w rong number of arguments')

Basically, with optparse, anything that involves positional arguments
has to be handled by the user.

It's also worth pointing out the better usage messages. Notice that the
output looked like::

$ scriptname.py -h
usage: scriptname.py [-h] [--save SAVE] package [package ...]

positional arguments:
package one of the packages to install

optional arguments:
-h, --help show this help message and exit
--save SAVE a file to save the package names to

With the optparse, you'd get something like::

$ scriptname.py -h
usage: scriptname.py [OPTIONS]

options:
-h, --help show this help message and exit
--save SAVE a file to save the package names to

The argparse module knows how to create a meaningful usage message
instead of just "%prog [OPTIONS]", and the argparse module knows about
positional arguments, so you can have help messages for them too.

Ok, enough propaganda for now. ;-)

STeVe
Aug 14 '06 #13
John Salerno wrote:
Yu-Xi Lim wrote:
I assume you're using a Debian-based distro with aptitude as the front
end. In which case, all dpkg operations should be logged in
/var/log/dpkg.log

Yes, I'm using Ubuntu. But I checked this log file and I'm a bit
confused. It has a lot of listings for 5-31-06, but I didn't even
install Linux until last Saturday. The next date after 5-31 is 8-5-06,
and I know I installed things between last Saturday and Aug. 5.

(But this is OT, so don't worry about it.)
I'm wondering about the need to "output the bash command to the
terminal". It would probably suffice if your Python script just spawned
an instance of the shell with the necessary command line. Take a look at
the subprocess module.

But this really calls for a bash script:

#!/bin/bash
echo $@ >/path/to/manual_install. log
sudo aptitude install $@
Shorter than the equivalent Python code. You could probably declare this
as a function in your bash initialization files too, if you know how to
do this.

Hmm, interesting. I figured I could do this with a bash script, but I
don't know bash at all and I'm trying to stick with Python. I don't
quite understand your bash script (not familiar with the $@ syntax).

I think I'll take a look at the subprocess module, just for fun. :)
Hey John, Yu-Xi Lim's right. This is one of those (thankfully few)
cases where bash makes more sense to use than python (at least IMHO.)

To figure out about that $@, fire up your teminal and type "man bash"
("!man bash" in IPython) (BTW, apropos of nothing, "man bash" is one of
my all time favorite commands ever. I always think of some comic-book
hero/monster shouting it, "MAN BASH!!" lol. Anyway...)

So, now you're looking at the man page for bash. It's very very long
and ubergeeky. Deep and amazing mysteries are contained (and kind of
explained) within it. You want information on $@ so we'll use the
search incantation to find and reveal it.

Type "/\$@" without the quotes, then press return. (What this
means/does: "/" is the manpage search command, it uses a regular
expression syntax not dissimilar to python's own. "\" escapes the next
character ("$", in this case) and we need to do that because "$" is
regular expression syntax for "end of line". The "$@" will now match,
um, "$@" correctly.)

Once you press return, man will scroll to put the first occurance of
"$@" at the top of your terminal and highlight it. On my system it's
this line (I narrowed my terminal so that quoted portions wouldn't wrap
badly in this posting):

"$@" as explained below under Special Parameters.

So far so good, '"$@" as explained below' looks promising. Rather than
scrolling down to find this "Special Parameters" section, let's keep
using the search.

Press "n" to scroll to the next occurance of our pattern "$@". On my
system this brings me to:

separate word. That is, "$@" is equivalent to
"$1" "$2" ... If the double-quoted expansion

Ah ha! Scrolling up a few lines, we see:

@ Expands to the positional parameters, starting
from one. When the expansion occurs within
double quotes, each parameter expands to a
separate word. That is, "$@" is equivalent to
"$1" "$2" ... If the double-quoted expansion
occurs within a word, the expansion of the
first parameter is joined with the beginning
part of the original word, and the expansion
of the last parameter is joined with the last
part of the original word. When there are no
positional parameters, "$@" and $@ expand to
nothing (i.e., they are removed).

Not extraordinarily enlightening, maybe, but better than sitting in the
dark, lighting your farts. :-D (Hit "q" to exit man.)

Basically what this means is that $@ will become the positional
arguments that you pass to your script. You can play with this by
writing a simple bash script like this

#!/bin/bash
echo $@

and passing it args to see what it echos. (Remember to chmod +x it..)

So, long story short, Yu-Xi Lim's bash script echos your package names
to the /path/to/manual_install. log file (">>" in bash means "append the
output of the command to the left to the file on the right",) then it
calls aptitude with those same package names.

It's simple, short, and to-the-point. The equivalent python script
would be much longer, for no appreciable gain. I write most of my tiny
little helper scripts in python, but in this case, bash is the clear
winnar. (And on *nix. man pages are your best friend. Plus you get to
feel all l33t when you grok them. lol)

Peace,
~Simon

Aug 14 '06 #14
Simon Forman wrote:
It's simple, short, and to-the-point. The equivalent python script
would be much longer, for no appreciable gain. I write most of my tiny
little helper scripts in python, but in this case, bash is the clear
winnar. (And on *nix. man pages are your best friend. Plus you get to
feel all l33t when you grok them. lol)
Thanks for the info! I might grudgingly decide to use a bash script in
this case. :)

And yes, it seems every time I ask a Linux question, everyone points me
to a man page. Sometimes I find them difficult to decipher, but they are
still a great help.
Aug 14 '06 #15
John Salerno wrote:
Simon Forman wrote:
It's simple, short, and to-the-point. The equivalent python script
would be much longer, for no appreciable gain. I write most of my tiny
little helper scripts in python, but in this case, bash is the clear
winnar. (And on *nix. man pages are your best friend. Plus you get to
feel all l33t when you grok them. lol)

Thanks for the info! I might grudgingly decide to use a bash script in
this case. :)
You're welcome. lol :)
And yes, it seems every time I ask a Linux question, everyone points me
to a man page. Sometimes I find them difficult to decipher, but they are
still a great help.
Yup. When I started with Linux, man pages were one of those things I
resisted... until I started actually reading them. Then I kicked
myself for not starting sooner. :)

Neat trick: man -k <search term>
Shows you man pages matching your search term (I think it's the same
thing as the "apropos" command.) It searches the command names and
summary lines.

Peace,
~Simon

Aug 14 '06 #16
Simon Forman wrote:
Neat trick: man -k <search term>
Ah, so much command line magic to learn! Maybe I should just go back to
Windows....or maybe not. ;)
Aug 14 '06 #17

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

Similar topics

6
3583
by: Avi Berkovich | last post by:
Hello, I was unable to use popen2.popen4 to grab python.exe's (2.3) output, for starts, it doesn't show the version information at the beginning and won't return anything when writing to the stdin pipe, it seems that if I give it some error nous expression, the pipe would return the exception data, though nothing else comes through. A friend of mine also tried this using win32api on delphi, and got the same result.
3
4217
by: Tuang | last post by:
I'd like to create my own mini "IDE" for working with several programming languages that provide interactive "toplevel" command line interpreters, such as Python, Ruby, Lisp, Scheme, OCaml, etc. (For those who haven't played with them, these languages -- unlike C, Java, C#, or Perl -- are designed to let you carry on an interactive conversation with them, so you can run each function in your app independently and interactively from a...
5
16967
by: Good Man | last post by:
Hi there I am trying to execute a custom-built java program on my linux server via PHP. Basically, a user uploads files via PHP, and then the java program performs some action on these files. I have successfully had other operations performed on these files by using backticks, ie: $doit = `my exec command`;
4
2009
by: fivestars | last post by:
Hi there. I'm computer science student at the end of my degree. I'm new about python. I've a question for all of you. Do you know how to write, from python code, on a unix(linux) terminal on specified coordinates? And also: is it possible to override, from python code, something on a
4
10514
by: Peter Nimmo | last post by:
Hi, I am writting a windows application that I want to be able to act as if it where a Console application in certain circumstances, such as error logging. Whilst I have nearly got it, it doesn't seem to write to the screen in the way I would expect. The output is:
17
3380
by: Matt | last post by:
Hello. I'm having a very strange problem that I would like ot check with you guys. Basically whenever I insert the following line into my programme to output the arguments being passed to the programme: printf("\nCommand line arguement %d: %s.", i , argv ); The porgramme outputs 3 of the command line arguements, then gives a segmentation fault on the next line, followed by other strange
3
1331
sokoun
by: sokoun | last post by:
Hi all, I am wondering whether we can start terminal by using command line or not? if we can what is the command to open the terminal process? for example if we want to run Konqueror we type Konqueror in command, so if we want to start the terminal what is the command that we use? sokoun.
0
1278
by: dinesh1440 | last post by:
I want to execute all the command that I can execute in command prompt or terminal through PHP. exec() and system() work only for some of the commands. I am working in linux. I installed offline Blast program. I can run this program only from command prompt or terminal and for several hundred files I need to do this. So I want to run this dynamically through programming. But I found that blast program does not work either with exec() or with...
0
9620
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
10104
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...
0
9912
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
8934
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
6715
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
5354
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
5482
by: adsilva | last post by:
A Windows Forms form does not have the event Unload, like VB6. What one acts like?
2
3609
muto222
by: muto222 | last post by:
How can i add a mobile payment intergratation into php mysql website.
3
2850
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.