Skip to content Skip to sidebar Skip to footer

How To Run Bash Commands Using Subprocess.run On Windows

I want to run shell scripts and git-bash commands using subprocess.run(), in python 3.7.4. When I run the simple example on the subprocess documentation page this happens: import s

Solution 1:

I found that I can run commands using ...Git\bin\bash.exe instead of the ...\Git\git-bash.exe, like this:

import subprocess
subprocess.run(['C:\Program Files\Git\\bin\\bash.exe', '-c','ls'], stdout=subprocess.PIPE)

CompletedProcess(args=['C:\\Program Files\\Git\\bin\\bash.exe', '-c', 'ls'], returncode=0, stdout=b'README.md\n__pycache__\nconda_create.sh\nenvs\nmain.py\ntest.sh\nzipped\n')

Solution 2:

Try this

p = subprocess.Popen(("ls", "-l"), stdout=subprocess.PIPE)
nodes = subprocess.check_output(("grep"), stdin=p.stdout)
p.wait()

Solution 3:

  • ls is Linux shell command for listing files and directories
  • dir is Windows command line command for listing files and directories

Try to run dir in Windows command line. If it works, try to run the same command using python subprocess:

import subprocess

subprocess.run(["dir"])

Solution 4:

For a machine with Windows Operating System, Try the following

import subprocess
subprocess.run(["dir", "/p"], shell=True)

"ls" is replaced with "dir", "-l" is replaced with "/l" and the "shell" is set to true

For a machine with Linux/Mac Operating System, Try the following

import subprocess
subprocess.run(["ls", "-l"])

Post a Comment for "How To Run Bash Commands Using Subprocess.run On Windows"