Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Using WSL bash from within python

Tags:

I'm using windows 10 and while working on a new project, I need to interact with WSL(Ubuntu on windows) bash from within python (windows python interpreter).

I tried using subprocess python library to execute commands.. what I did looks like this:

import subprocess
print(subprocess.check_call(['cmd','ubuntu1804', 'BashCmdHere(eg: ls)']))#not working

print(subprocess.check_output("ubuntu1804", shell=True).decode())#also not working

The expected behavior is to execute ubuntu1804 command which starts a wsl linux bash on which I want to execute my 'BashCmdHere' and retrieve its results to python but it just freezes. What am I doing wrong ? or how to do this ?

Thank you so much

like image 736
Mag_Amine Avatar asked Aug 28 '19 13:08

Mag_Amine


1 Answers

Found 2 ways to achieve this:

A correct version of my code looks like this

#e.g: To execute "ls -l"
import subprocess
print(subprocess.check_call(['wsl', 'ls','-l','MaybeOtherParamHere']))

I should have used wsl to invoke linux shell from windows aka bash then my command and parameters in separated arguments for the subprocess command.

The other way which I think is cleaner but may be heavier is using PowerShell Scripts:

#script.ps1
param([String]$folderpath, [String]$otherparam)
Write-Output $folderpath
Write-Output $otherparam
wsl ls -l $folderpath $otherparam

Then to execute it in python and get the results:

import subprocess


def callps1():
    powerShellPath = r'C:\WINDOWS\system32\WindowsPowerShell\v1.0\powershell.exe'
    powerShellCmd = "./script.ps1"
    #call script with argument '/mnt/c/Users/aaa/'
    p = subprocess.Popen([powerShellPath, '-ExecutionPolicy', 'Unrestricted', powerShellCmd, '/mnt/c/Users/aaa/', 'SecondArgValue']
                         , stdout=subprocess.PIPE, stderr=subprocess.PIPE)
    output, error = p.communicate()
    rc = p.returncode
    print("Return code given to Python script is: " + str(rc))
    print("\n\nstdout:\n\n" + str(output))
    print("\n\nstderr: " + str(error))


# Test
callps1()

Thank you for helping out

like image 179
Mag_Amine Avatar answered Nov 03 '22 01:11

Mag_Amine