如何用Pexpect编译C代码和运行编译代码?

How to compile C code and run the compile code with Pexpect?

我有 C 代码,我想编译然后 运行 它具有预期。我该怎么做??但是这个命令不起作用。

child = pexpect.spawn("gcc -o pwn code.c)

通过这种方式你可以看到你的输出

In [1]: import pexpect    
In [12]: pexpect.spawn("gcc ab.c")                                                                                                                    
Out[12]: <pexpect.pty_spawn.spawn at 0x7efcf4787130>
In [13]: pexpect.spawn("./a.out")                                                                                                                     
Out[13]: <pexpect.pty_spawn.spawn at 0x7efcf432d8e0>

In [14]: pexpect.spawn("./a.out").read()                                           
Out[14]: b'Hello world'

要执行该命令,您可能需要通过在 pexpect.spawn:

之后添加 child.expect_exact() 来向前移动预期光标

NOTE - Tested on Ubuntu 20.04 using Python 3.8

import sys

import pexpect

print("Method 1:")
child = pexpect.spawn("gcc -o pwn code.c")
child.logfile_read = sys.stdout.buffer
child.expect_exact(["$", pexpect.EOF, ])
child = pexpect.spawn("./pwn")
child.logfile_read = sys.stdout.buffer
child.expect_exact(["$", pexpect.EOF, ])

输出:

Method 1:
Hello, world!

但是,您可能想尝试这些替代方案,而不是生成两个 children;在你的情况下,因为你不需要保持 child 进程打开,我推荐方法 3,使用 pexpect.run:

import sys

import pexpect

print("Method 2:")
child = pexpect.spawn("bash")
# Shows all output
child.logfile_read = sys.stdout.buffer
child.expect_exact("$")
child.sendline("gcc -o pwn2 code.c")
child.expect_exact("$")
child.sendline("./pwn2")
child.expect_exact("$")
child.close()

print("Method 3:")
list_of_commands = ["gcc -o pwn3 code.c",
                    "./pwn3", ]
for c in list_of_commands:
    command_output, exitstatus = pexpect.run(c, withexitstatus=True)
    if exitstatus != 0:
        print("Houston, we've had a problem.")
    print(command_output.decode().strip())

输出:

Method 2:
$ gcc -o pwn2 code.c
$ ./pwn2
Hello, world!
$
Method 3:

Hello, world!

Process finished with exit code 0