【问题标题】:How to compile C code and run the compile code with Pexpect?如何编译 C 代码并使用 Pexpect 运行编译代码?
【发布时间】:2022-01-18 09:05:10
【问题描述】:

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

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

【问题讨论】:

  • 能不能先编译C代码,再从python运行?
  • In [1]: import pexpect In [12]: pexpect.spawn("gcc ab.c") Out[12]: In [13]: pexpect.spawn("./a.out") Out[13]: In [14]: pexpect.spawn("./a.out").read() Out[14 ]: b'Hello world'
  • @QuantumMecha 先生,我得试试Pexpect

标签: python bash terminal pexpect


【解决方案1】:

要执行该命令,您可能需要通过在pexpect.spawn 之后添加child.expect_exact() 来将pexpect 光标向前移动:

注意 - 使用 Python 3.8 在 Ubuntu 20.04 上测试

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!

但是,您可能想尝试这些替代方案,而不是生成两个孩子;在您的情况下,由于您不需要保持子进程处于打开状态,因此我建议使用方法 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

【讨论】:

    【解决方案2】:

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

    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'
    

    【讨论】:

    • 在我的系统上,它没有编译c代码
    • 代码执行没有任何错误但是代码没有被编译
    • 您使用的是哪个操作系统?我可以看到你正在做的路径和代码吗?我正在使用 ubuntu,它在我的系统中运行,并证明我已经发送了代码。
    • 谢谢先生,它成功了
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2021-09-27
    • 2011-06-03
    • 1970-01-01
    • 1970-01-01
    • 2015-01-29
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多