简体   繁体   中英

Pexpect carriage return issue


I have create one application that uses pexpect to retrieve output of some commands
One of the example of commands that i do is the following:

ps aux

And this is a bit of the output directly from pexpect

root 28039 0.0 0.1 57780 3056 ? Ss Sep26 0:04 /opt/services/s^M
root 28093 0.5 0.4 131688 6492 ? Ss Sep26 93:25 /opt/services/s^M
root 28125 0.2 0.8 222680 13012 ? Ssl Sep26 36:21 /opt/services/s^M

The problem here is that output is truncated and not only added the '\\r' in the middle of the output.
This might be solved using "| cat" in the command, but i need a solution that do not involve redirecting the output to cat.

I have seen this happen when i send a big command but the output is always the command with the ^M in the middle.

Is there any change that i can do in the terminal or in pexpect in order to solve this problem?

Use

ps axuww

The ww means

   w               Wide output. Use this option twice for unlimited width.

import pexpect
child = pexpect.spawn('ps auxww')
while True:
    try:
        child.expect('\r\n')
        print(child.before)
    except pexpect.EOF:
        break

as discussed in comments, the ps aux command is truncating its output due to the implicit terminal width setting. You can prevent this by telling ps to use wide output (the ww in ps auxww ) or increasing the terminal width (pexpect setwinsize() ) as discussed in the comments.

The ^M in the output is your UNIX-like operating system displaying the DOS-style CR/LF line endings. This is because pexpect actually operates a psuedo-TTY device. Something explained in the pexect documentation

The best way to match the end of a line is to look for the newline: "\\r\\n" (CR/LF). Yes, that does appear to be DOS-style. It may surprise some UNIX people to learn that terminal TTY device drivers (dumb, vt100, ANSI, xterm, etc.) all use the CR/LF combination to signify the end of line. Pexpect uses a Pseudo-TTY device to talk to the child application, so when the child app prints "\\n" you actually see "\\r\\n" .

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