[Python] How can I call Python script on remote server with xp_cmdshell?

Discussão em 'Python' iniciado por Stack, Julho 7, 2025.

  1. Stack

    Stack Membro Participativo

    Trying to call python script on ServerB from local server and getting this error like below, searched all about this error, figured out that it's about env variables, but not clear where in xp_cmdshell to change this setting. This is existing legacy process which uses EXEC sp_executesql @sqlcmd call from sql server, it works OK for other processes, all security consideration are taken care of. In error output I see mixup of local and remote pathes, my local path to python has Program Files in it, on remote ServerB python installed right under c\Python312.
    See that it determined sys.executable correctly but rest are set for local ? I understand that I need to silence local pythonpath, but not clear how, can anybody help?

    Thanks this is my simple test1.py:

    import socket
    #if 'PYTHONHOME' in os.environ:
    # del os.environ['PYTHONHOME']
    print (socket.gethostname())
    ### end of test1.py

    EXEC sp_executesql @sqlcmd;
    EXEC xp_cmdshell '\\ServerB\C$\Python312\python.exe \\ServerB\C$\python_Scripts\test1.py'


    Python path configuration:

    PYTHONHOME = 'C:\\Program Files\\Python37' ###<< local path !!!!!!!
    PYTHONPATH = (not set)
    program name = '\\ServerB\C$\Python312\python.exe '
    isolated = 0
    environment = 1
    user site = 1
    safe_path = 0
    import site = 1
    is in build tree = 0
    stdlib dir = 'C:\Program Files\Python37\Lib'
    sys._base_executable = '\\\\ServerB\\C$\\Python312\\python.exe '
    sys.base_prefix = 'C:\\\\Program Files\\\\Python37' ###<< local !!!????
    sys.base_exec_prefix = 'C:\\\\Program Files\\\\Python37' ###<< local !!!????
    sys.platlibdir = 'DLLs'
    sys.executable = '\\\\ServerB\\C$\\Python312\\python.exe '
    sys.prefix = 'C:\\\\Program Files\\\\Python37' ###<< local !!!????
    sys.exec_prefix = 'C:\\\\Program Files\\\\Python37' ###<< local !!!????
    sys.path = [
    '\\\\ServerB\\C$\\Python312\\python312.zip',
    'C:\\Program Files\\Python37\\DLLs', ###<< local !!!????
    'C:\\Program Files\\Python37\\Lib', ###<< local !!!????
    '\\\\ServerB\\C$\\Python312',
    ]


    and output:

    Fatal Python error: init_fs_encoding: failed to get the Python codec of the filesystem encoding
    Python runtime state: core initialized
    ModuleNotFoundError: No module named 'encodings'
    NULL
    Current thread 0x000059fc (most recent call first):
    <no Python frame>
    NULL

    Continue reading...

Compartilhe esta Página