I am new to python and I am trying to write a simple program that would cd from my home directory to another directory, run an ls command and then return to my home directory. The OS is Redhead linux 5.4. I am using python 2.4.3.

I tried this first:
import os
os.system("cd /opt/WindRiver")
os.system("ls")
os.system("cd /home/harry")

The cd command did not work as the ls command listed the files in my home directory, not the new directory.

I then try:
import os
os.chdir("/opt/WindRiver")
os.system("ls")
os.chdir("/home/harry")

chdir worked but looks likes it started a new shell and stayed in the new directory. I had to manually enter the exit command to exit the current shell.

Any suggestions on how to make it work?

Thanks,
Harry Yuen

That's because the directory was changed in the bash shell (os.system) and not in the python shell. Why not just use
os.system("ls /opt/WindRiver")
or, since we now use subprocess
subprocess.call("ls /opt/WindRiver", shell=True)

You can use python's
os.chdir("/opt/WindRiver")
but it is better to always use absolute path names to avoid the type of error that you posted originally.

That's because the directory was changed in the bash shell (os.system) and not in the python shell. Why not just use
os.system("ls /opt/WindRiver")
or, since we now use subprocess
subprocess.call("ls /opt/WindRiver", shell=True)

You can use python's
os.chdir("/opt/WindRiver")
but it is better to always use absolute path names to avoid the type of error that you posted originally.

I am also trying to run a bash script inside the /opt/WindRiver directory. The script calls another script inside the same directory. That would make it necessary to cd into that directory first. In bash shell, I would do:
$ cd /opt/WindRiver
$ ./wrenv.sh -p vxworks-6.7

How would you handle that in python?

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.