running shell command in python under git-bash not working well

Question:

I am using python3 under git-bash environment, and sometimes it does not run shell command well.

#!/usr/bin/env python3


import subprocess as sp

print("hello")

print(sp.getoutput("ls -l"))  # This works.

print(sp.getoutput("date"))   # This hangs and cannot terminate with ctrl-c.

This does not happen when running under normal linux/bash environment.

Then I come across this one: Python not working in the command line of git bash.

I can run using "winpty python …", however it still cannot terminate even with ctrl-c.

I take back, getoutput("date") hangs but check_output works.

Asked By: user180574

||

Answers:

You are needlessly running those commands with a shell.

Prefer this form:

print(sp.check_output(["ls", " -l"]))

print(sp.check_output(["date"]))

Answered By: J_H
Categories: questions Tags: , , ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.