How do I pass a variable to an external program

C

Cameron Laird

Hi

I would like to pass a variable to an external program i.e.

os.system('cd $variable')

However this doesnt work, I cant figure it out, any ideas?
.
.
.
In the short term,
os.system('cd %s' % variable)
is probably what you think you want.
 
G

Gerrit Holl

Rigga said:
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.
 
R

Rigga

Hi

I would like to pass a variable to an external program i.e.

os.system('cd $variable')

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

Cheers

Rigga
 
R

Rigga

Cameron said:
.
.
.
In the short term,
os.system('cd %s' % variable)
is probably what you think you want.
Wow thanks for the fast response that works a treat, now i just gotta find
out how you run more than one command on a line i.e.
os.system('cd %s' 'ls -lt')
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

No members online now.

Forum statistics

Threads
473,744
Messages
2,569,484
Members
44,903
Latest member
orderPeak8CBDGummies

Latest Threads

Top