[Python-Dev] Alternative to os.system that takes a list of strings?
Guido van Rossum
guido@digicool.com
Mon, 05 Feb 2001 09:34:51 -0500
> Hi. I've found it convenient to use the function below to make system
> calls, as I sometimes the strings I need to pass as arguments confuse
> the shell used in os.system. I was wondering whether it's worth passing
> this upstream. The main problem with doing so is that I have no idea
> how to implement it on Windows, as I can't use the os.fork and os.wait*
> functions in that context.
>
> Alex.
Hi Alex,
This functionality is alrady available through the os.spawn*() family
of functions. This is supported on Unix and Windows.
BTW, what do you mean by "upstream"?
--Guido van Rossum (home page: http://www.python.org/~guido/)
> import os
>
> def system(command, args, environ=os.environ):
>
> '''The 'args' variable is a sequence of strings that are to be
> passed as the arguments to the command 'command'.'''
>
> # Fork off a process to be replaced by the command to be executed
> # when 'execve' is run.
> pid = os.fork()
> if pid == 0:
>
> # This is the child process; replace it.
> os.execvpe(command, [command,] + args, environ)
>
> # In the parent process; wait for the child process to finish.
> return_pid, return_value = os.waitpid(pid, 0)
> assert return_pid == pid
> return return_value
>
> if __name__ == '__main__':
>
> print system('/bin/cat', ['/etc/hosts.allow', '/etc/passwd'])