3

I've tried the following three ways to change a directory and it never changes. has anyone else had this problem?

import pysftp
cnopts = pysftp.CnOpts()
cnopts.hostkeys = None
host = 'server1.mydomain.com' # altered
with pysftp.Connection(host=host, **get_credentials(), cnopts=cnopts) as connection:

    connection.execute('cd project')
    print(connection.execute('pwd'))      #---> [b'/home/jm\n']

    connection.execute('cd /home/jm/project')
    print(connection.execute('pwd'))      #---> [b'/home/jm\n']

    connection.cd('project')
    print(connection.execute('pwd'))      #---> [b'/home/jm\n']

    with connection.cd('project'):
        print(connection.execute('pwd'))  #---> [b'/home/jm\n']

'/home/jm/project/' does exist by the way. I've also trid many other combinations that I didn't list here.

It doesn't make any sense to me, can you help?

MetaStack
  • 3,266
  • 4
  • 30
  • 67

1 Answers1

3

Try chdir() instead. Per the docs:

cd(remotepath=None)
context manager that can change to a optionally specified remote directory and restores the old pwd on exit.

chdir(remotepath)
change the current working directory on the remote

So:

connection.chdir('/home/jm/project')
Ben Whaley
  • 32,811
  • 7
  • 87
  • 85
  • In the end though, that didn't work either. maybe its a problem with pysftp talking to centos 7 or something. What did work was this: I have to move to the directory and immediately execute my desired command. otherwise, it moves me back directly after this command finishes executing. `connection.execute('cd /home/jm/project ; ls')` In other words its as if there's no persistence of the current working directory change. – MetaStack Aug 17 '18 at 16:15
  • cd in this case is context aware, like documentation say: [link](https://pysftp.readthedocs.io/en/release_0.2.9/cookbook.html#pysftp-cd). So it reverts to the original path when function ends. – Yanek Jun 07 '19 at 13:43