0

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.

tripleee
  • 175,061
  • 34
  • 275
  • 318
user180574
  • 5,681
  • 13
  • 53
  • 94
  • Have you tried to run `date` command in git bash ? – Philippe Dec 19 '22 at 09:05
  • Is the copy of python3 being started a native Windows executable or a cygwin/msys/&c executable? (If it's the latter, the copy of `date` it starts should be the same as the one bash starts; if it's the former, then not so much). Another important difference is that for a Cygwin python, anywhere it's told to run a shell will start `sh`; if it's a Windows one, it'll try to start `cmd`. I would only expect `sp.getoutput("ls -l")` to ever work with a Windows-built Python; for a Cygwin one or or a more legitimately UNIXy system it needs to be `sp.getoutput(["ls", "-l"])` to work at all. – Charles Duffy Dec 19 '22 at 17:22
  • (as a worse-practice alternative, `sp.getoutput("ls -l", shell=True)` should also work on UNIXy systems, or Python interpreters built for cygwin/msys/etc) – Charles Duffy Dec 19 '22 at 17:24
  • Anyhow -- calling native-Windows `date` from a more UNIXy Python interpreter, or a more UNIXy `date` from a native-Windows Python interpreter is liable to cause surprises like those discussed in the other question you linked. – Charles Duffy Dec 19 '22 at 17:26

1 Answers1

1

You are needlessly running those commands with a shell.

Prefer this form:

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

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

J_H
  • 17,926
  • 4
  • 24
  • 44
  • I notice that it could be a git-bash/python problem, as in https://stackoverflow.com/questions/32597209/python-not-working-in-the-command-line-of-git-bash – user180574 Dec 19 '22 at 16:43
  • There's no implicit `shell=True` when there's only a single string passed, so the OP is _not_ using a shell -- `shell=True` needs to be explicit for that. I suspect that the OP is depending on a Windows-ism (the platform takes argument vector as a shell-like string, not a list). Passing a list tells Python to perform escaping that Microsoft's libc will parse back to the desired argument vector if the program being run doesn't override the parsing. – Charles Duffy Dec 19 '22 at 16:54