Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
224 views
in Technique[技术] by (71.8m points)

python 2.7 - OS.symlink support in windows

I downloaded python 2.7.1 from the python website and installed it to windows. When attempting to symlink a file, I find that it is not supported.

However, I found this issue, and saw that it was fixed. Will this be implemented, and if so when? I'm running windows Vista.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

There's a way to fix this, patching the os module on your's python environment start.

The function to create symlinks is already avaliable from Windows API, you only need do call it.

During python's startup, an attempt is made to import a module named sitecustomize.py, on the site-packages directory. We will use this hook to attach our function to the os module.

Put this code on the file sitecustomize.py:

import os

__CSL = None
def symlink(source, link_name):
    '''symlink(source, link_name)
       Creates a symbolic link pointing to source named link_name'''
    global __CSL
    if __CSL is None:
        import ctypes
        csl = ctypes.windll.kernel32.CreateSymbolicLinkW
        csl.argtypes = (ctypes.c_wchar_p, ctypes.c_wchar_p, ctypes.c_uint32)
        csl.restype = ctypes.c_ubyte
        __CSL = csl
    flags = 0
    if source is not None and os.path.isdir(source):
        flags = 1
    if __CSL(link_name, source, flags) == 0:
        raise ctypes.WinError()

os.symlink = symlink

Your Python process needs to be started with enabled "Create symbolic links" privilege, this is not a Python issue, every program that claims to use this Windows API will need it. This can be done running your Python interpreter from an elevated cmd.exe. A better alternative is to grant the privilege to the user, provided your Windows edition ships with the required Group Policy editor (gpedit.msc). See the screenshot below. You can adjust the value to include whatever user or security group requires this kind of privilege without compromising on the security of the administrative accounts.

The group policy editor

Note: Code snippet from here


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...