2012-06-15 2 views
1

쉘이 있고 pwd를 사용하여 어떤 디렉토리에 있는지 보여줍니다. 내가 디렉토리에있을 때 내가 폴더 /home/foo/mime이있는 경우 그러나 그것은 심볼릭 링크가 있다는 그것이 내가 호출 할 때이 /usr/share/mime에 심볼릭 링크 있다는 원래 디렉토리되지에게 심볼릭 링크파이썬에서 bash의 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] 

을 보여

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

I 얻었다는/usr/쉘 주/MIME

내 코드는 다음과 같다 :

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 원본 경로 대신 symlink에 경로를 반환하는 방법이 있습니까?

+2

확실하지 않은 경우 : [os.getcwd()] (http://docs.python.org/library/os.html#os-file-dir) 현재 작업 디렉토리를 제공합니다. – bpgergo

+0

또한 심볼릭 링크를 지원합니다 iirc – Jharwood

답변

4

현재 쉘에서만 기호 링크를 사용하여 현재 디렉토리에 액세스한다는 것을 알고 있습니다. 이 정보는 일반적으로 자식 프로세스로 전달되지 않으므로 현재 경로 만 실제 경로로 알 수 있습니다.

이 정보를 하위 프로세스에 알리려면 인수 나 환경 변수를 통해 전달하는 방법을 정의해야합니다. 쉘에서 PWD를 내보내는 것만으로도 효과가있을 수 있습니다. Popen에서

+0

대단한 것 같아요,이'sub.Popen ([ '/ bin/bash', '-c', 'cd % s && % s '% (경로, 명령)], stdout = sub.PIPE, stderr = sub.STDOUT)'작동합니다. – jcubic

3

symlink를 해결하려면 ZSH 및 BASH (동작은 동일)의 예제 인 아래 pwd -P을 사용하고 싶을 것입니다. FreeBSD의의/빈/비밀번호를 사용

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 

그래도 난이 얻을 : 당신은 심볼릭 링크가 해결되지 않은하려는 경우

[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 디렉토리가 아닌 symlink를 원한다. – jcubic

+0

처음에는 bash에서 호출 할 때 첫 번째 예제처럼 pwd가 작동하지만 파이썬에서는 호출하지 않습니다. – jcubic

1

사용 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는, 실제로 위와 같이 쉘 자체를 요구 이외의 파이썬 쉘 pwd을 얻을 수있는 방법, 없습니다.

관련 문제