2012-06-15 48 views
1

我有一個shell,我用pwd來顯示我在哪個目錄下。但是當我在目錄是,它是一個符號鏈接顯示它原來的目錄而不是符號連接pwd從python擴展符號鏈接

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 /分享/ 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返回符號鏈接而不是原始目錄。

+2

不知道它有幫助:[os.getcwd()](http://docs.python.org/library/os.html#os-file-dir)會給你當前的工作目錄。 – bpgergo

+0

它也支持符號鏈接iirc – Jharwood

回答

4

只有當前shell知道它使用符號鏈接來訪問當前目錄。這些信息通常不會傳遞給子進程,因此只能通過其真實路徑瞭解當前目錄。

如果您希望子流程知道這些信息,您需要定義一種方法來傳遞它,例如通過參數或環境變量。從shell導出PWD可能正常。

+0

偉大的想法,我用這個'sub.Popen(['/ bin/bash','-c','cd%s &&% s'%(path,command)],stdout = sub.PIPE,stderr = sub.STDOUT)'並且它工作。 – jcubic

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 

[email protected] ~/music % pwd 
/home/tom/music 
[email protected] ~/music % pwd -P 
/mnt/ftp/music 

中使用FreeBSD的/ bin /密碼我得到這個雖然:

[email protected] ~/music % /bin/pwd 
/mnt/ftp/music 
[email protected] ~/music % /bin/pwd -P 
/mnt/ftp/music 
[email protected] ~/music % /bin/pwd -L 
/home/tom/music 

因此,也許您的PWD(1)支持-L太多,如果你想要的符號鏈接解決,因爲這個版本假設-P默認 ?

+0

我得到了像使用'pwd -P'的行爲,我不想那樣做。我想要符號鏈接而不是orignal目錄。 – jcubic

+0

當我從pash中調用pwd時,你的第一個例子就像你的第一個例子,但不是來自python – jcubic

1

使用shell=TruePopen

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,有沒有辦法讓蟒蛇殼pwd,比實際要求像上面的外殼本身以外。