简体   繁体   中英

Print stdout in Python without shell escape sequences

I'm using sh to run git commands inside a Python script.

In [1]: from sh import git

In [2]: s = git("log", "-1", pretty="format:%h %s")

In [3]: print s
4f14a66 basic debug page

This seems to work as expected. However, using this in a Django template gives [?1h= 4f14a66 basic debug page[m [K[?1l> . I tried to see what characters were in this string using repr() , to no avail:

In [4]: print repr(s)
4f14a66 basic debug page

It turns out commands in sh return a RunningCommand that has a .stdout attribute:

In [5]: type(s)
Out[5]: sh.RunningCommand

In [7]: s.stdout
Out[7]: '\x1b[?1h\x1b=\r4f14a66 basic debug page\x1b[m\r\n\r\x1b[K\x1b[?1l\x1b>'

How do I get "4f14a66 basic debug page" ie the string without the escapes? Running the command from Bash is fine:

$ git log -1 --pretty="format:%h %s"
4f14a66 basic debug page

According to this GitHub issue , correct solution to the problem is to use _tty_out=False :

>>> str(git('show', format='%cN', s=True))
'\x1b[?1h\x1b=\rHonza Javorek\x1b[m\r\n\r\x1b[K\x1b[?1l\x1b>'

>>> str(git('show', format='%cN', s=True, _tty_out=False))
'Honza Javorek\n'

This is also solution for my duplicate question: Using sh, git show returns special characters - how to get plain output?

s.stdout in the REPL will not print it but display its repr() . Use print s.stdout to get what you are looking for.

If you do not want any escape codes consider executing it using subprocess.call() - with stdout not being a tty most programs do not output any escape sequences.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM