5
5

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 5 years have passed since last update.

Pythonで絶対URLを相対URLに変換

Posted at

開発環境から本番サーバーへアップする場合など、リンク等が相対パスで書かれていた方がいい時も。

起点となるファイルorディレクトリから、相対パスを求める関数はこんな感じでしょうか。

import sys, os
from urlparse import urlparse, urlunparse

def relurl(absolute, origin):
    a = urlparse(absolute)
    o = urlparse(origin)

    # ドメインが違う時、相対パスは考えにくいのでそのまま返却
    if a.netloc != o.netloc:
        return absolute

    relative = os.path.relpath(a.path, os.path.dirname(o.path))
    return urlunparse(('','',relative) + a[3:])

def main():
    params = sys.argv
    print relurl(params[1], params[2])

if __name__ == '__main__':
    main()
5
5
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
5
5

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?