来自 Python 的 Bash 的 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符号链接而不是物理目录的返回路径。

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

如果您希望子流程知道此信息,则需要定义一种传递它的方法,例如通过参数或环境变量。从外壳中导出 PWD 可能只是工作。

如果要

解析符号链接,则可能需要使用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 ?

Popen 中使用 shell=True

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,除了像上面那样实际询问 shell 本身之外,没有办法在 python 中获取 shell pwd

最新更新