8

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

2
  • I believe once you have WSL installed you can execute bash commands from the normal cmd window by prepending the command bash. With this approach you will not need to launch WSL just leverage the normal cmd Commented Aug 28, 2019 at 13:26
  • from a cmd or PowerShell command prompt everything works fine .. but when I try to invoke ubuntu1804 from python .. it just freezes Commented Aug 28, 2019 at 13:28

3 Answers 3

4

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

Sign up to request clarification or add additional context in comments.

Comments

1

What about:

print(subprocess.check_call(['ubuntu1804', 'run', 'BashCmdHere(eg: ls)'])) #also try without "run" or change ubuntu1804 to wsl

Or

print(subprocess.check_call(['cmd', '/c', 'ubuntu1804', 'run', 'BashCmdHere(eg: ls)']))#also try without "run" or change "ubuntu1804" to "wsl"
# I think you need to play with quotes here to produce: cmd /c 'ubuntu1804 run BashCmdHere(eg: ls)'

First, try to call your command from cmd.exe to see the right format and then translate it to Python.

1 Comment

In your first suggestion, the cmd "run" turns to be unknown, additionally I found that I shall use "wsl" instead of "ubuntu1804" to invoke the Linux shell, ubuntu1804 considers everything after it as an argument instead of command However if I remove run and change ubuntu1804 to wsl, surprisingly it works so here is your up-vote. Also, I've found another way to achieve my objective involving PowerShell scripts, I'm posting it bellow as well as the proper way I found to do it using whats above .. cheers
-2
os.system('bash')

I figured this out by accident.

2 Comments

As it’s currently written, your answer is unclear. Please edit to add additional details that will help others understand how this addresses the question asked. You can find more information on how to write good answers in the help center.
This doesn't answer the question that was asked, which was how to execute a command inside WSL such as ls or a script and "retrieve its results to python". Also, note that the bash.exe command to launch WSL has been deprecated. You should use the replacement wsl.exe command.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.