Why are some Unix commands not working when called from within Python? (command not found)

I often want to execute Unix commands from Python, but I recently found that some commands were not found. An example is the "limit" command:

$ echo $SHELL
/bin/tcsh
$ limit vmemoryuse 1000m
$ python
Python 2.7.3 (default, Aug  3 2012, 20:09:51) 
[GCC 4.1.2 20080704 (Red Hat 4.1.2-50)] on linux2
Type "help", "copyright", "credits" or "license" for more information.
>>> import os
>>> os.system("echo $SHELL")
/bin/tcsh
0
>>> os.system("limit vmemoryuse 1000m")
sh: limit: command not found
32512
>>>

      

Another example is the setenv command. Why don't these commands work inside Python? I have tried using the "os" and "subprocess" modules with no success. Does anyone know of another module or method that will allow me to successfully invoke these commands from Python?

+3


source to share


1 answer


This is because some shell commands are not really programs, but internal shell commands.

Classic example:: cd

if it were an external program, this would change the current directory of the new process, not the one in the shell, so it cannot be an external program.

Roughly speaking, there are two types of internal shell commands:

  • Teams that are implemented with efficiency shell, but it still exists as a separate program: true

    , false

    , test

    , sleep

    ...
  • Commands that alter membrane environment and therefore can not be made from the child process: cd

    , umask

    , setenv

    , ulimit

    ...

The commands in the first category are quite shell specific. There are not many teams in the second category.

See the man page of the corresponding shell (for example man bash

) for details .

And if you want to know about a specific command run:



$ type -a <command>

      

The type is bugism, I don't know the equivalent in tcsh, but it which

is an external program, so this:

$ which -a <command>

      

will show you if your command exists as an external program, but it knows nothing about internal shells.

If you want the functionality of an internal command (type 2 above) in your Python program, you need to use the appropriate system call. I hope it will already be available in some module. If not, you need to write your own wrapper in C.

About your specific commands:

  • Environment ( setenv

    and getenv

    ) can be driven by means os.environ

    or os.getenv

    , os.putenv

    etc.
  • For process limits ( limit

    ) see the resource module .
+8


source







All Articles