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
192k37 gold badges319 silver badges370 bronze badges
asked Dec 19, 2022 at 5:11
user180574
6,24417 gold badges65 silver badges111 bronze badges
1 Answer 1
You are needlessly running those commands with a shell.
Prefer this form:
print(sp.check_output(["ls", " -l"]))
print(sp.check_output(["date"]))
answered Dec 19, 2022 at 5:32
J_H
21.4k5 gold badges29 silver badges52 bronze badges
Sign up to request clarification or add additional context in comments.
2 Comments
user180574
I notice that it could be a git-bash/python problem, as in stackoverflow.com/questions/32597209/…
Charles Duffy
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.default
datecommand in git bash ?dateit 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 startsh; if it's a Windows one, it'll try to startcmd. I would only expectsp.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 besp.getoutput(["ls", "-l"])to work at all.sp.getoutput("ls -l", shell=True)should also work on UNIXy systems, or Python interpreters built for cygwin/msys/etc)datefrom a more UNIXy Python interpreter, or a more UNIXydatefrom a native-Windows Python interpreter is liable to cause surprises like those discussed in the other question you linked.