Pushd Through Os.system
Solution 1:
In Python 2.5 and later, I think a better method would be using a context manager, like so:
import contextlib
import os
@contextlib.contextmanagerdefpushd(new_dir):
previous_dir = os.getcwd()
os.chdir(new_dir)
try:
yieldfinally:
os.chdir(previous_dir)
You can then use it like the following:
with pushd('somewhere'):
printos.getcwd() # "somewhere"printos.getcwd() # "wherever you started"
By using a context manager you will be exception and return value safe: your code will always cd back to where it started from, even if you throw an exception or return from inside the context block.
You can also nest pushd calls in nested blocks, without having to rely on a global directory stack:
with pushd('somewhere'):
# do something
with pushd('another/place'):
# do something else
# do something back in"somewhere"
Solution 2:
Each shell command runs in a separate process. It spawns a shell, executes the pushd command, and then the shell exits.
Just write the commands in the same shell script:
os.system("cd /directory/path/here; run the commands")
A nicer (perhaps) way is with the subprocess
module:
from subprocess import Popen
Popen("run the commands", shell=True, cwd="/directory/path/here")
Solution 3:
pushd
and popd
have some added functionality: they store previous working directories in a stack - in other words, you can pushd
five times, do some stuff, and popd
five times to end up where you started. You're not using that here, but it might be useful for others searching for the questions like this. This is how you can emulate it:
# initialise a directory stack
pushstack = list()
defpushdir(dirname):
global pushstack
pushstack.append(os.getcwd())
os.chdir(dirname)
defpopdir():
global pushstack
os.chdir(pushstack.pop())
Solution 4:
I don't think you can call pushd
from within an os.system()
call:
>>>import os>>>ret = os.system("pushd /tmp")
sh: pushd: not found
Maybe just maybe your system actually provides a pushd
binary that triggers a shell internal function (I think I've seen this on FreeBSD beforeFreeBSD has some tricks like this, but not for pushd
), but the current working directory of a process cannot be influenced by other processes -- so your first system()
starts a shell, runs a hypothetical pushd
, starts a shell, runs ls
, starts a shell, runs a hypothetical popd
... none of which influence each other.
You can use os.chdir("/home/path/")
to change path: http://docs.python.org/library/os.html#os-file-dir
Solution 5:
No need to use pushd
-- just use os.chdir
:
>>>import os>>>os.getcwd()
'/Users/me'
>>>os.chdir('..')>>>os.getcwd()
'/Users'
>>>os.chdir('me')>>>os.getcwd()
'/Users/me'
Post a Comment for "Pushd Through Os.system"