Search code examples
pythonsshoperating-system

How to set different filesystem for python os.path module?


I'm developing a script that auto-deploys my Django project from my Windows machine to my local Raspberry server.

Amongst the steps, there's a python script that has to be copyied to the server, and executed there. I execute it through an SSH call from paramiko module:

client.exec_command('python ' + '/home/myname/projects/example_app/script.py')

This is one of the lines the executed script:

import os
import subprocess

sp.run("python " + os.path.join("/home/myname/projects", "example_app", "manage.py collectstatic"))

However, I get the following erro:

python: can't open file 'E:\\home\\myname\\projects\\example_app\\manage.py': [Errno 2] No such file or directory

Weirdly enough, seems like the os.path module is joining paths considering my Windows filesystem, even though the script is called from within the Linux server. Ok, I don't know about the SSH implementation, and I can accept that. My question is: is there a way to manually set the OS for os.path module?


Solution

  • from pathlib import Path, PurePosixPath, PureWindowsPath
    def test():
        file = PurePosixPath('/home/myname/projects') / "example_app" / "manage.py"
        sp.run(f'python {file} collectstatic')
    

    Note that collectstatic isn't part of the filename but is an argument passed to Python. So it shouldn't be part of the pathname.

    The module pathlib provides Path, PurePosixPath, and PureWindowsPath. The first provides what's on the current platform. The latter two have more limited functionality, but can be used to build appropriate filenames.