Haj Nasser
Haj Nasser

Reputation: 304

Use Python in ubuntu to show contents of a directory

I have a .py file in the home directory which contains these three lines:

 import os

 os.system("cd Desktop/")
 os.system("ls")

and I want it to "ls" from the "Desktop" directory but it shows contents of the /home directory.
I looked at these pages:
Calling an external command in Python
http://ubuntuforums.org/showthread.php?t=729192
but I could not understand what to do. Can anybody help me?

Upvotes: 1

Views: 1296

Answers (2)

nickpapior
nickpapior

Reputation: 782

You have to consider that os.system executes the commands in a sub-shell. Hence 1) python starts a sub-shell, 2) the directory is changed, 3) then the sub-shell is completed, 4) return to previous state.

To force the current directory change you should do:

os.chdir("Desktop")

Always try and do it by other means that through os.system (os.listdir), or also by doing other than subprocess (which is an excellent module for command control in the shell)

Upvotes: 0

Sebastian Wozny
Sebastian Wozny

Reputation: 17526

The two calls are separate from each other. There is no context kept between successive invocations of os.system because a new shell is spawned for every call. First os.system("cd Desktop/") switches directories to Desktop and exits. Then a new shell executes ls in the original folder.

Try chaining your commands with &&:

import os

os.system("cd Desktop/ && ls")

This will show the contents of directory Desktop.


Fabric

If your application is going to be heavy on os usage you might consider using python-fabric. It allows you to use higher level language constructs like contextmanagers to make command line invocations easier:

from fabric.operations import local
from fabric.context_managers import lcd

with lcd("Desktop/"): # Prefixes all commands with `cd Desktop && `
    contents=local("ls", capture=True)

Upvotes: 1

Related Questions