简体   繁体   中英

Is there a way in python to use os.path operations for an OS that is not your current?

The situation: I am currently using paramiko to do some fancy sftp stuff and often find myself compiling path names for remote files. I think that there might be a more intelligent way of doing this. The question: Is there a way in python to use os.path operations for an OS that is not your current os? I would like to ultimatly be able to go remotehost.os.path."some operation"

As the big Note at the top of the docs says:

Since different operating systems have different path name conventions, there are several versions of this module in the standard library. The os.path module is always the path module suitable for the operating system Python is running on, and therefore usable for local paths. However, you can also import and use the individual modules if you want to manipulate a path that is always in one of the different formats. They all have the same interface:

  • posixpath for UNIX-style paths
  • ntpath for Windows paths
  • macpath for old-style MacOS paths
  • os2emxpath for OS/2 EMX paths

Obviously things like ntpath.lexists aren't going to work on a POSIX system, but things like join , basename , etc. will.

If you don't know what format the remote server expects, and don't have any way to figure it out, posixpath is usually a safe bet. sftp , and Paramiko's similar functionality, will always handle POSIX paths; if you're using an ssh shell, cmd.exe and many of the command-line tools you'd want to run (including Python scripts) will be able to handle them on Windows, and the same is true for OS/2, and of course old-style Mac doesn't even have a shell you can ssh to.

I suggest you take a good look at fabric .

  • it is leveraging paramiko for the low-level stuff (transport/ssh/sftp).
  • it is a very good alternative for running a Task , or automation.
  • they are working on remote execution hooks (open issue) .
    • execnet , pushy , pyro ... and other parallel processing libs.

Under the hood, fabric uses posixpath.join() , since Windows does support / as a directory separator . They had the same problem you did and changed from os.path.join to posixpath.join() in this commit .

Features of fabric :

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM