...making Linux just a little more fun!

Mailbag

This month's answers created by:

[ Anderson Silva, Matt Woodson, Arslan Farooq, Ben Okopnik, Henry Grebler, René Pfeiffer, Mulyadi Santosa, Aioanei Rares, Steve Brown ]
...and you, our readers!

Our Mailbag


Many thanks for your bash permission article

Ben Okopnik [ben at okopnik.com]


Fri, 11 Mar 2011 00:02:07 -0500

[cc'd to the Answer Gang]

Hi, Long -

On Thu, Mar 10, 2011 at 10:54:18AM -0800, Long Chow wrote:

> Hello Ben Okopnik,
> 
> Yesterday I bumped into a su (substitute user) permission error similar
> to your Apr. 2000 article, "Cannot execute /bin/bash: Permission denied".
> I was attempting to run an expect script in non-root user mode on Fedora 8:
> 
>   su netter -c "expect try.exp"
> 
> and it failed:
> 
>   couldn't read file "try.exp": permission denied
> 
> No problem if I run:
>   su root -c "expect try.exp"
>   expect try.exp
> 
> I pored over permission related avenues for the whole day and failed.
> It was around midnight when I googled upon your article that my hope was
> rekindled.
> 
> So the first thing coming into work today...
> Using your approach (especially strace), I found the execution bit for others
> for /root
> was not set.  After setting it, my non-root mode command string started to
> work!

That's actually not a good solution; the correct permissions for /root are 0700. Setting it to 0701, as you have, allows other users to enter that directory - a really bad idea!

ben@Jotunheim:~$ ls -ld /root
drwx------ 11 root root 4096 2011-03-10 21:14 /root
ben@Jotunheim:~$ head -n 1 /root/.bashrc
head: cannot open `/root/.bashrc' for reading: Permission denied

OK, this is what's supposed to happen. But here's what happens when I change the permissions as you specified:

ben@Jotunheim:~$ sudo chmod 0701 /root
[sudo] password for ben: 
ben@Jotunheim:~$ head -n 1 /root/.bashrc
# ~/.bashrc: executed by bash(1) for non-login shells.

Whoops...

I suspect that the right solution for you would be to put 'try.exp' somewhere other than /root; then you won't have to do anything with those permissions (other than hopefully set them back as quickly as possible.)

Ben

-- 
                       OKOPNIK CONSULTING
        Custom Computing Solutions For Your Business
Expert-led Training | Dynamic, vital websites | Custom programming
  443-250-7895   http://okopnik.com   http://twitter.com/okopnik

[ Thread continues here (2 messages/3.66kB) ]


Crowdsource + open source to preserve US war documents

Ben Okopnik [ben at linuxgazette.net]


Fri, 18 Mar 2011 22:18:15 -0400

On Sat, Mar 19, 2011 at 02:00:47AM +0000, Jimmy O'Regan wrote:

> http://www.readwriteweb.com/archives/crowdsourcing_us_war_papers.php
> 
> Source here: https://github.com/chnm/Scripto

Beautiful. Whether Open Source /qua/ Open Source takes over the world or not, its key methods - i.e., accomplishing major tasks by winning brainshare - already have.

-- 
* Ben Okopnik * Editor-in-Chief, Linux Gazette * http://LinuxGazette.NET *


Problem with installing a local module

Ben Okopnik [ben at okopnik.com]


Mon, 14 Feb 2011 20:30:43 -0500

Hi, Rui -

I assume that you wanted to send this question to The Answer Gang rather than asking me for a private consult (those tend to be expensive :), so I've forwarded it there. Please direct any further emails about it there (tag@lists.linuxgazette.net), and I'll try to answer your questions.

On Tue, Feb 08, 2011 at 11:33:53AM +0000, Rui Fernandes wrote:

> Dear Ben Okopnik,
>  
> I've read your article "Installing Perl Modules as a Non-Root User", and
> regarding including the "myperl" in @INC" it worked. But now I have a problem,
> that maybe you can help.
> I▓m trying to install a local module in a webserver that isn▓t mine. I get no
> error with the following Makefile.PL

Do you mean when you run 'make', 'make test', 'make install', or all of them?

> CODE:
>  #!/usr/local/bin/perl
> use 5.008007;
> use ExtUtils::MakeMaker;
> # See lib/ExtUtils/MakeMaker.pm for details of how to influence
> # the contents of the Makefile that is written.
> WriteMakefile(
>     NAME              => 'Kepler',
>     VERSION_FROM      => 'lib/Kepler.pm', # finds $VERSION
>     PREREQ_PM         => {}, # e.g., Module::Name => 1.1
>     ($] >= 5.005 ?     ## Add these new keywords supported since 5.005
>       (ABSTRACT_FROM  => 'lib/Kepler.pm', # retrieve abstract from module
>        AUTHOR         => 'Rui Fernandes <rui.kepler@gmail.com>') : ()),
>     LIBS              => ['-L/home/username/usr/local/lib -lswe'], # e.g.,
> '-lm'
> #    LIBS              => ['-lswe'], # e.g., '-lm'
>     DEFINE            => '', # e.g., '-DHAVE_SOMETHING'
>     INC               => '-I/home/username/usr/local/include', # e.g., '-I. -I/
> usr/include/other'
>     INSTALL_BASE      => '/home/username/myperl',
> #    DISTVNAME         => 'perl_kepler', #
>  # Un-comment this if you add C files to link with later:
>     # OBJECT            => '$(O_FILES)', # link all the C files too
> );
>  
> END CODE
>  
> But when I run the test script, the module isn't found, not even in the "myperl
> /lib" directory.

I'm having trouble parsing that last sentence. Do you mean the module is actually not in myperl/lib, or does your test script not find it?

I suspect that it's the latter. If that's the case, then what's happening is that your web server isn't seeing the correct path. This often happens because the actual path to your home directory is not necessarily the same thing as you see when you log in via, say, SSH. For example, in one of my former webservers, the path reported by 'pwd' when I was in my home directory was '/home/ben' - but the real path was something like '/homepages/41/d322536930/'. As a result, using '/home/ben/myperl' as part of my 'use lib' statement was worthless: the web server didn't know anything about a path like that.

Perhaps the easiest way to find out what the server is seeing as your real path is to look at the server environment. Here's an easy way to do that with Perl:

[ ... ]

[ Thread continues here (1 message/4.22kB) ]


2-cent Tip: Octal permissions in "ls"

Ben Okopnik [ben at linuxgazette.net]


Sat, 26 Mar 2011 22:53:50 -0400

I've always wondered why "ls" doesn't just have this as an option. Got tired of wondering, so I went ahead and wrote it.

This script is intended to be a drop-in replacement for "ls" - in other words, just put it somewhere accessible and alias it to 'ls'. It takes all the same options that 'ls' does (no wonder; it simply passes the entire argument string to 'ls'), and works in the same way, unless the first option that you specify - and it must be specified by itself - is "-O" (capital "o", not a zero.) In that case, it does all the same stuff but reformats the output a little - just the filetype/permissions section. I haven't done a huge amount of testing on it, so it might be fragile in some unexpected places (reports would be appreciated). Seems OK, though, so I'm releasing it to the unsuspecting world. Enjoy.

#!/usr/bin/perl -w
# Created by Ben Okopnik on Sat Mar 26 19:00:46 EDT 2011
use strict;
 
if ($ARGV[0] ne '-O'){ exec '/bin/ls', @ARGV } else { shift; }
 
for (qx#/bin/ls @ARGV#){
    my ($t, $p, $r) = /^(.)([rwxsStT-]+)(\s+\d+\s+\w+.+)$/;
    print and next unless $p;
 
    my $out = 0;
    my %d = map {split//} qw/sx S- r4 w2 x1 -0/;
    $out += 01000 if $p =~ y/tT/x-/;
    $out += 02000 if $p =~ s/(s)(?=.{3})$/$d{$1}/i;
    $out += 04000 if $p =~ s/(s)(?=.{6})$/$d{$1}/i;
 
    $p =~ s/([rwx-])// and $out += $d{$1} * oct($_) for (100)x3, (10)x3, (1)x3;
 
    printf "[%s] %04o  %s\n", $t, $out, $r;
}
-- 
* Ben Okopnik * Editor-in-Chief, Linux Gazette * http://LinuxGazette.NET *

[ Thread continues here (7 messages/10.83kB) ]


Odd system load situation, LG February 2011 (#183)

Ben Okopnik [ben at okopnik.com]


Thu, 10 Feb 2011 08:47:21 -0500

Hi, Hans-Peter -

On Mon, Feb 07, 2011 at 06:52:06PM -0500, hanspetersorge@aim.com wrote:

> Hi Ben,
> 
> I just read the thread - no idea how to append..

Just send your message to The Answer Gang (tag@lists.linuxgazette.net), and we'll add it to the next issue. I've cc'd this response there, so it'll get used that way.

> My 2-cents:  USB is being polled.

You're probably right - and very likely, it's getting polled very rapidly, given the task. I'm not sure what could be done about that - some kernel setting, perhaps?

> strace -p ....  might give you some clues too.

The question is, what would I attach it to? 'rsync' wouldn't make a whole lot of sense, since it's not involved in USB polling.

Ben

-- 
                       OKOPNIK CONSULTING
        Custom Computing Solutions For Your Business
Expert-led Training | Dynamic, vital websites | Custom programming
  443-250-7895   http://okopnik.com   http://twitter.com/okopnik

[ Thread continues here (5 messages/9.12kB) ]


Duplicate LG mailing list reports

Ben Okopnik [ben at linuxgazette.net]


Fri, 1 Apr 2011 13:46:14 -0400

On Fri, Apr 01, 2011 at 10:14:43AM -0700, Mike Orr wrote:

> I got two monthly reminders today about my LG mailing-list
> subscriptions. Both to my same email address, both with the same list
> URL (lists.linuxgazette.net), but with different passwords and
> different lists subscribed. One of the passwords works, the other one
> doesn't. So is there a phantom old server sending out reminders?

Yep. Except it's not coming from the LG address; it's the difference between the 'From ' and the 'From:' addresses (the latter can be faked.)

> Here's the headers for the message with the working password:
[snip]

> Return-Path: <mailman-bounces@lists.linuxgazette.net>
^^^^^^^^^^^^^^^^^^^^^^

> Here are the headers for the message with the non-working password:
[snip]

> Return-Path: <mailman-bounces@linuxmafia.com>
^^^^^^^^^^^^^^

-- 
* Ben Okopnik * Editor-in-Chief, Linux Gazette * http://LinuxGazette.NET *


Talkback:183/lg_foolish.html

Marcello Romani [marcello.romani at libero.it]


Wed, 02 Feb 2011 22:44:01 +0100

Hi, I had a horror story similar to Ben's one, about two years ago. I backed up a PC and reinstalled the OS with the backup usb disk still attached. The OS I was reinstalling was a version of Windows (2000 or XP, I don't remember right now). When the partition creation screen appeared, the list items looked a bit different from what I was expecting, but as soon as I realized why, my fingers had already pressed the keys, deleting the existing partitions and creating a new ntfs one. Luckily, I stopped just before the "quick format" command... Searching the 'net for data recovery software, I came across TestDisk, which is target at partition table recovery. I was lucky enough to have wiped out only that portion of the usb disk, so in less than an hour I was able to regain access to the all of my data. Since then I always "safely remove" usb disks from the machine before doing anything potentially dangerous, and check "fdisk -l" at least three times before deciding that the arguments to "dd" are written correctly...

Marcello Romani TAG mailing list TAG@lists.linuxgazette.net http://lists.linuxgazette.net/listinfo.cgi/tag-linuxgazette.net


2D CAD DraftSight Now Available for Linux

Ben Okopnik [ben at linuxgazette.net]


Thu, 10 Mar 2011 02:38:58 -0500

This was submitted yesterday, but I figure that it's interesting enough for anyone here that might be interested in high-end CAD (I dimly recall a conversation about it here...) that I'd give you folks an early preview. IIRC, Dassault Systemes produces the CAD system thar was used to design the Airbus.

----- Forwarded message from Christina Feeney <cfeeney@shiftcomm.com> -----

Date: Wed, 9 Mar 2011 10:11:59 -0500
From: Christina Feeney <cfeeney@shiftcomm.com>
To: "'ben@linuxgazette.net'" <ben@linuxgazette.net>
Subject: 2D CAD DraftSight Now Available for Linux
Hi Ben,

The wait is over – free 2D CAD software DraftSight is officially available for Linux! The demand for this operating system has been overwhelming and DraftSight is thrilled to be able to offer it to everyone today. The news just crossed the wire early this morning and I wanted to make sure you had all of the details. The full release is embedded below. Please let me know if you have any questions or would like screenshots.

Thanks!

Christina

Dassault SystХmes’ DraftSight Now Available for Linux

Linux Users Can Now Create, Edit and View DWG Files with DraftSight

VиLIZY-VILLACOUBLAY, France, – March 9, 2011 – Dassault SystХmes (DS) (Euronext Paris: #13065, DSY.PA), a world leader in 3D and Product Lifecycle Management (PLM) solutions, today announced the availability of a beta release of DraftSight for Linux. DraftSight is a no-cost 2D CAD product for CAD professionals, students and educators that can be downloaded at DraftSight.com.

DraftSight for Linux allows users to create, edit and view DWG files. DraftSight generally takes a few minutes to download and runs on multiple operating systems, including Linux and Mac OS in beta, and Windows XP, Windows Vista and Windows 7 in general release.

“We’re very excited to finally announce to the DraftSight community the availability of Linux in beta for DraftSight,” said Aaron Kelly, senior director, DraftSight, Dassault SystХmes. “We’ve been working on the Linux version since the launch of DraftSight and have seen a significant rise in demand for this over the last few months. It’s been our objective since the start to respond to users by providing them with products that will meet their needs.

DraftSight beta users have access to no-cost Community Support available within the DraftSight open, online SwYm community where they can access support and training resources, along with an environment to interact, ask questions and share their opinions. The DraftSight community is one of the first social networks designed by engineers for engineers, designers and architects.

For more information, please visit DraftSight.com. Also, check out DraftSight on Facebook and Twitter.

###

Christina Feeney | Senior Account Executive| SHIFT Communications |

phone: 617.779.1805 | mobile: 617.240.9181 | email: cfeeney@shiftcomm.com |

web: www.shiftcomm.com| blog: www.pr-squared.com | ----- End forwarded message -----

[ ... ]

[ Thread continues here (1 message/3.49kB) ]


Talkback:184/grebler1.html

Henry Grebler [henrygrebler at optusnet.com.au]


Sat, 05 Mar 2011 08:13:20 +1100

Hi Francis,

-->I see one possible typo in a not-yet-much-used one: --> -->""" -->I have just changed this alias to --> --> alias w '(pwd; /bin/pwd ) | uniq; df -h | tail -1' --> -->I often also want to know whether I'm on a local disk or not. -->""" --> -->That probably wants to be "df -h ." (at least on recent-ish Debian and -->RedHat systems).

Absolutely correct. Thanks for that.

-->And if you are likely to be on a system where the "Filesystem" -->name is quite long (such as "/dev/mapper/VolGroup00-LogVol00"), then -->using "tail -n +2" might be handy too -- but I can't comment on the -->portability/compatibility of that option across systems.

Perfect!

Another example of "write in haste, repent at leisure." I should stick to presenting the tried and true - and forget about improvising.

Thank you for your fixes. I will adjust my files immediately.

Cheers, Henry TAG mailing list TAG@lists.linuxgazette.net http://lists.linuxgazette.net/listinfo.cgi/tag-linuxgazette.net


LG - what's next?

Ben Okopnik [ben at linuxgazette.net]


Mon, 16 May 2011 11:49:06 -0400

Hello, all -

After a number of years of running LG, I've reached a stopping point: I can't continue producing it, for a variety of interconnected reasons. In short, the group of people currently involved in making LG happen has become so small that almost the entire thing has fallen on me - and the technical side of producing it is so complicated that my current level of business and other life involvement does not leave me with enough spare time to do it. As a result, there was no LG issue for this month - and despite giving it my best shot over the past two weeks, I have still not managed to release one.

That seems to me to be an extraordinarily clear signal that the time has come for me to step down. Whether that means that someone else gets to take over, or whether LG simply ends at this point, I don't know. I've tried to prevent the latter... but it appears that I have reached the end of what I can do in that regard. Whether it continues or not has to become someone else's concern. I am no longer able to carry the load.

I'm sure that someone with better management skills than mine could organize and structure a working team that would distribute the load; someone with more time could replace the totally outdated and rather arcane production system, which currently takes many hours of work to release an issue (by contrast, a CMS such as WordPress could easily be configured to replicate the LG site structure, and production - as well as adding proofreaders and editors - would become a trivial matter rather than the complicated and fragile SVN-based system currently in place.) I would be happy to advise whoever takes over, assuming that someone does.

The current state, however, is that LG is no longer being actively produced by me. My most sincere apologies to anyone that I have let down.

-- 
* Ben Okopnik * Editor-in-Chief, Linux Gazette * http://LinuxGazette.NET *

[ Thread continues here (35 messages/74.71kB) ]


SVN authentication

Ben Okopnik [ben at linuxgazette.net]


Wed, 16 Mar 2011 16:49:29 -0400

Hi, all -

I'm hoping that someone here has experience in setting up SVN. I'm running into several issues in setting it up for LG... frankly, it's mostly my own mental state more than anything else; 'buffer full' at the moment. Unsurprising, after a couple of weeks of full-time training course development, setting up LG in its new home, and learning a new language during all that. My brain is pretty cooked, and I desperately need a break. I'm just hoping that someone here has a shortcut; it shouldn't be that difficult, really.

What I'd like to do is set it up so that I don't have to create a system account for everyone who needs SVN access. We don't even need web access to the repo; we just need our editors and proofreaders to authenticate via whatever mechanism SVN uses, pull a copy of the repo, and check their work back in whenever they're done with it.

Any help - and the best of all possible world would be an offer like "I'd be happy to do it for you!" - would be very welcome.

-- 
* Ben Okopnik * Editor-in-Chief, Linux Gazette * http://LinuxGazette.NET *

[ Thread continues here (18 messages/35.79kB) ]


Padding a string in Perl

Ben Okopnik [ben at okopnik.com]


Mon, 9 May 2011 20:44:09 -0400

On Tue, May 10, 2011 at 01:00:10AM +0100, Jimmy O'Regan wrote:

> I've got a bunch of photos from a Picasa installation, that have face
> regions marked in the .picasa.ini file that I've been trying to get
> into a more useful form.
> 
> So far, I can convert to the format used in Microsoft's photo region
> schema (which is about as close as it gets to a standard):
> 
> sub padrect($) {
^^^

You probably shouldn't do that. Unless you know exactly why you're doing it (hint: "I want this sub to only take a single scalar argument" is not a good reason) and what the side effects and the pitfalls are. For the full treatment, see "perldoc perlsub". The takehome rule of thumb is "don't". :)

> The method I'm using to pad out the string is horrible and ugly - is
> there a nicer way to do it?

Yep. Thomas' advice is right on the dot; in this kind of situations, 'pack' (and often 'vec') are your very good friends.

Ben

-- 
                       OKOPNIK CONSULTING
        Custom Computing Solutions For Your Business
Expert-led Training | Dynamic, vital websites | Custom programming
  443-250-7895   http://okopnik.com   http://twitter.com/okopnik


Talkback:184/lg_bytes.html

Ben Okopnik [ben at linuxgazette.net]


Sat, 5 Mar 2011 02:15:44 -0500

On Thu, Mar 03, 2011 at 10:05:43PM +0000, Jimmy O'Regan wrote:

> IBM's Watson, DeepBlueQA, Wins on Jeopardy!
> 
> Um... wouldn't it have been worth noting that Watson ran (in part) on Linux?

<blonde moment>Why, is that important?</blonde moment>

That's what I get for trying to get an issue out the door and not having anyone backstop me. We really need a post-production reviewer besides just me.

> There's an article with some of the details here:
> http://www.stanford.edu/class/cs124/AIMagzine-DeepQA.pdf

The Linux Gazette is always happy to accept submissions, corrections, and contributions from qualified volunteers. :)

-- 
* Ben Okopnik * Editor-in-Chief, Linux Gazette * http://LinuxGazette.NET *


Stubborn or Fried Memory card?

Ben Okopnik [ben at okopnik.com]


Tue, 26 Apr 2011 09:56:37 -0400

On Tue, Apr 26, 2011 at 02:36:47PM +1000, Amit Saha wrote:

> 
> Disk /dev/sdc: 6469 MB, 6469189632 bytes
> 200 heads, 62 sectors/track, 1018 cylinders, total 12635136 sectors
> Units = sectors of 1 * 512 = 512 bytes
> Sector size (logical/physical): 512 bytes / 512 bytes
> I/O size (minimum/optimal): 512 bytes / 512 bytes
> Disk identifier: 0x00000000
^^^^^^^^^^

> Disk /dev/sdc doesn't contain a valid partition table
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^

Presuming that it did have one, and had a reasonable identifier, it looks like your card's not readable. Assuming that there's no "protect" switch on it - you did look for one, right? - I suspect that it has failed. That is, it can be read enough to determine its physical characteristics - I don't know how the two processes differ, I only know that they do - but you can't access its storage. In other words, it's junk.

> Anything else I can try? Any info appreciated.

Try a raw read.

# See if you can copy the first 512 bytes
sudo dd if=/dev/sdc of=/tmp/mbr bs=512 count=1
 
# If that succeeds, then back it up, quick!
sudo dd if=/dev/sda of=/tmp/sdc_backup.raw bs=4096

Ben

-- 
                       OKOPNIK CONSULTING
        Custom Computing Solutions For Your Business
Expert-led Training | Dynamic, vital websites | Custom programming
  443-250-7895   http://okopnik.com   http://twitter.com/okopnik

[ Thread continues here (5 messages/8.44kB) ]


The Cognitive Style of Unix

Ben Okopnik [ben at linuxgazette.net]


Wed, 16 Mar 2011 00:18:52 -0400

On Wed, Mar 09, 2011 at 04:38:18PM +0100, Predrag Ivanovic wrote:

> <courtesy of LWN>
> 
> "One of the most deeply held beliefs in the culture of *nix (and everything that springs from it)
> is that the steep learning curve pays off. Yes, the tools seem cryptic and “hard-to-use”, with hardly
> any crutches for the beginner. But if you stick with it and keep learning you will be rewarded.
> When you grok the power of economical command lines, composability and extensibility, you’re glad
> you didn’t run back to the arms of the GUI on the first day. It was worth it.[...]"
> 
> Yes it was, and still is :).
> 
> Full text at
> http://blog.vivekhaldar.com/post/3339907908/the-cognitive-style-of-unix

This is, or closely related to, the thing that attracted me to Linux in the first place. In the Windows world, you're either a user - which is defined by a very narrow, small set of pointy-clicky skills and not much if any understanding of the mechanisms you use - or you're some sort of a "wizard", which gets defined in all sorts of arcane ways, mostly meaning "knows some stuff beyond what users know." All that "stuff", however, doesn't form any kind of a coherent whole: it was all chunks and bits and pieces, no relation of anything to anything else. The only choices, if you wanted more than the minimum, were 1) specialize - meaning something like learning a certain language or a given application, or 2) gather enough critical mass of random stuff until you formed a gravity well of your own and could pull out some sort of a related useful fact when a problem came along. All very haphazard, and somewhat akin to stumbling around in a dark dungeon until you found some treasure or (far more likely) ran into some kind of a monster.

YOU'RE TRAPPED IN A MAZE OF TWISTY PASSAGES, ALL ALIKE, AND YOU'RE LIKELY TO BE EATEN BY A GRUE.

(It is worth noting that I functioned in that world, professionally, for a number of years, all the way from a wet-behind-the-ears teenage computer repairman to working as CIO for an insurance company. This perspective is not formed by my desire to promote Linux; quite the opposite, if anything - I advocate Linux usage because I have this perspective, which was formed by long experience.)

[ ... ]

[ Thread continues here (1 message/4.86kB) ]


OMFG... G00G13'Z B33N H4XX0R3D!!!

Ben Okopnik [ben at linuxgazette.net]


Sun, 13 Mar 2011 22:01:04 -0400

http://www.google.com/webhp?hl=xx-hacker

Ran across this purely by accident. Wild. :)

-- 
* Ben Okopnik * Editor-in-Chief, Linux Gazette * http://LinuxGazette.NET *


Possible 2-cent tip: Opening files from the command line

Ben Okopnik [ben at linuxgazette.net]


Wed, 20 Apr 2011 09:52:25 -0400

On Wed, Apr 20, 2011 at 06:48:52PM +1000, Amit Saha wrote:

> 
>     # from http://stackoverflow.com/questions/54139[...]cting-extension-from-filename-in-python/
>     file_type = os.path.splitext(filename)[1]

I generally try to avoid importing modules if there's a built-in method that works just as well. In this case, you're importing "os" anyway, but this also works in scripts where you don't.

file_type = filename.split('.')[-1]

>     # Uses execlp so that the system PATH is used for finding the program file
>     # location
>     os.execlp(program,'',filename)

The main problem with this type of script is that you have to be a Python programmer to add a filetype/program pair. I'd suggest breaking out the dictionary as an easily-parseable text file, or adding a simple interface ("Unsupported filetype. What program would you like to use?") that updates the list.

> Is there any Linux command line tool which can easily do this?

Midnight Commander is quite good at this; in fact, I've used that functionality of 'mc' in some of my shell scripts for just this purpose. They use a mix of regex matching, MIME-type matching, and literal extension recognition to work with various files. E.g., the ".gz" extension in "foo.1.gz" doesn't tell you anything about the type of file that it is (a man page).

-- 
* Ben Okopnik * Editor-in-Chief, Linux Gazette * http://LinuxGazette.NET *

[ Thread continues here (8 messages/18.25kB) ]



Share

Talkback: Discuss this article with The Answer Gang

Copyright © 2011, . Released under the Open Publication License unless otherwise noted in the body of the article.

Published in Issue 186 of Linux Gazette, June 2011

Tux