How do I pass a variable to an external program

Gerrit Holl gerrit at nl.linux.org
Fri Oct 10 15:09:44 EDT 2003


Rigga wrote:
> I would like to pass a variable to an external program i.e. 

There are different possiblities to that.

> os.system('cd $variable')

Note that this does nothing. 'cd' only has consequences for the
current process, since it is a change directory. If you want to
change your directory, you need os.chdir instead.
See also: help(os.chdir)

> However this doesnt work, I cant figure it out, any ideas?

os.system is simply given a string, where spaces mark the different
arguments. You can put a variable into a string with several
methods:

s = "cd %s" % variable
s = "cd " + str(variable)
s = "cd +%(variable)s" % locals()

You can also call os.spawn instead of os.system. This way, you
pass a list or arguments (all strings) to the program, without
the problem that spaces may occur in one of them:

os.spawn("/bin/ls", ["ls", "/usr/local"])
See also: help(os.spawn)

Please look at the online documentation at python.org for more information
on string substitution, starting subprocceses, changing directories
and other things.

Gerrit.

-- 
121. If any one store corn in another man's house he shall pay him
storage at the rate of one gur for every five ka of corn per year.
        -- 1780 BC, Hammurabi, Code of Law
--
Asperger Syndroom - een persoonlijke benadering:
	http://people.nl.linux.org/~gerrit/
Kom in verzet tegen dit kabinet:
	http://www.sp.nl/





More information about the Python-list mailing list