Rakesh K
Rakesh K

Reputation: 8515

python fabric cd context manager does not work from Linux to Windows

I have a fabric task using which I need to run some commands on a remote Windows machine. In this task, I need to change the current working directory on the remote machine and I'm using cd context manager to do this. This works fine when run the fabric script from a Windows machine, but I get the following error when I run from a Linux/Mac machine:

The system cannot find the path specified.
Fatal error: run() received nonzero return code 1 while executing!

Here's my fabric script:

from fabric.api import run, env, cd

env.user = 'abc'
env.password = 'xyz'
env.shell = 'cmd.exe /c'

def task1():
    with cd('C:\\temp\\test'):
        run('dir')

What am I missing here and how can I make it work from Linux?

Upvotes: 0

Views: 710

Answers (2)

Evhz
Evhz

Reputation: 9275

Just as a hint, wouldn't this work?

from fabric.api import run, env, cd

env.user = 'abc'
env.password = 'xyz'
env.shell = 'cmd.exe /c'

def task1():
    # with cd('C:\\temp\\test'):
    run('cd C:\\temp\\test')
    run('dir')

In order to do an on-the-go fix on the _change_cwd method, this command

import os
print(os.sep)

# '/' in unix like
# '\' in windows like 

can help to have a system wise directory separator.

Upvotes: 1

Ismaïl Mourtada
Ismaïl Mourtada

Reputation: 472

Looking at Fabric's source code, here is the implementation of cd:

def cd(path):
    return _change_cwd('cwd', path)

def _change_cwd(which, path):
    path = path.replace(' ', '\ ')
    if state.env.get(which) and not path.startswith('/') and not path.startswith('~'):
       new_cwd = state.env.get(which) + '/' + path
    else:
        new_cwd = path
    return _setenv({which: new_cwd})

=> The new working directory has a mix of '\' and '/' characters, which Windows may misinterpret. If I'm not mistaken, and your Windows server version is recent enough, then it should accept the '/' slashes, so try to change your context instruction to cd('C:/temp/test')

If it doesn't work, then what is your Windows server's current directory ? You can figure it out by printing env.cwd. Maybe it is on another drive, but I doubt that...

Upvotes: 1

Related Questions