pwd来自python的bash扩展符号链接

时间:2012-06-15 09:25:19

标签: python bash shell interpreter pwd

我有一个shell,我使用pwd显示我在哪个目录。但是当我在目录中它是一个符号链接时,它显示原始目录而不是符号链接

import subprocess as sub

def execv(command, path):
    p = sub.Popen(['/bin/bash', '-c', command],
                    stdout=sub.PIPE, stderr=sub.STDOUT, cwd=path)
    return p.stdout.read()[:-1]

如果我有文件夹/home/foo/mime,那么当我打电话时它是/usr/share/mime的符号链接

execv('pwd', '/home/foo/mime')

我得到/ usr / share / mime

我的shell代码如下所示:

    m = re.match(" *cd (.*)", form['command'])
    if m:
        path = m.group(1)
        if path[0] != '/':
            path = "%s/%s" % (form['path'], path)
        if os.path.exists(path):
            stdout.write(execv("pwd", path))
        else:
            stdout.write("false")
    else:
        try:
            stdout.write(execv(form['command'], form['path']))
        except OSError, e:
            stdout.write(e.args[1])

我有JavaScript的客户端

(可能返回命令和新路径的结果,因为JSON会更好)。

有没有办法让pwd返回路径到符号链接而不是原始目录。

3 个答案:

答案 0 :(得分:5)

只有当前的shell知道它正在使用符号链接来访问当前目录。此信息通常不会传递给子进程,因此它们只通过其实际路径知道当前目录。

如果您希望子进程知道此信息,则需要定义一种传递方式,例如通过参数或环境变量。从shell导出PWD可能会起作用。

答案 1 :(得分:3)

如果你想解决符号链接,你可能想要使用pwd -P,下面是ZSH和BASH的例子(行为相同)。

ls -l /home/tom/music
lrwxr-xr-x  1 tom  tom  14  3 říj  2011 /home/tom/music -> /mnt/ftp/music

cd /home/tom/music

tom@hal3000 ~/music % pwd
/home/tom/music
tom@hal3000 ~/music % pwd -P
/mnt/ftp/music

使用FreeBSD的/ bin / pwd我得到了这个:

tom@hal3000 ~/music % /bin/pwd 
/mnt/ftp/music
tom@hal3000 ~/music % /bin/pwd -P
/mnt/ftp/music
tom@hal3000 ~/music % /bin/pwd -L
/home/tom/music

所以也许你的pwd(1)也支持-L,如果你想要没有解析符号链接,因为这个版本默认假设-P?

答案 2 :(得分:1)

shell=True中使用Popen

import os
from subprocess import Popen, PIPE

def shell_command(command, path, stdout = PIPE, stderr = PIPE):
  proc = Popen(command, stdout = stdout, stderr = stderr, shell = True, cwd = path)
  return proc.communicate() # returns (stdout output, stderr output)

print "Shell pwd:", shell_command("pwd", "/home/foo/mime")[0]

os.chdir("/home/foo/mime")
print "Python os.cwd:", os.getcwd()

输出:

Shell pwd: /home/foo/mime
Python os.cwd: /usr/share/mime

AFAIK,没有办法在python中获取shell pwd,除了实际上像上面一样询问shell本身。