python实现 linux 执行命令./test启动进程,进程运行中,输入参数s, 再输入参数1, 再输入参数exit, 获取进程运行结果重定向写入到文件

要在 Python 中实现执行 `./test` 启动进程,并在进程运行中依次输入参数 `s`、`1`,最后输入参数 `exit`,并将进程的输出结果重定向写入到文件,你可以使用 `subprocess` 模块。以下是一个示例代码:

import subprocess

# 启动 test 进程
test_process = subprocess.Popen(["./test"], stdin=subprocess.PIPE, stdout=subprocess.PIPE, stderr=subprocess.PIPE, text=True)

# 输入参数 s
test_process.stdin.write("s\n".encode('utf-8'))
test_process.stdin.flush()

# 输入参数 1
test_process.stdin.write("1\n".encode('utf-8'))
test_process.stdin.flush()

# 输入参数 exit
test_process.stdin.write("exit\n".encode('utf-8'))
test_process.stdin.flush()

# 获取进程输出结果
output, error = test_process.communicate()
output_lines = output.decode("utf-8").splitlines()
for i in output_lines:
     print(i)

# 将参数和结果写入文件
with open(order_result, "w",encoding="utf-8") as file:
    for line in output_lines:
        file.write(line)
        file.write("\n")

# 等待进程退出
test_process.wait()

在这段代码中,我们使用 `subprocess.Popen` 来启动 `./test` 进程,并使用 `stdin.write` 方法向进程输入参数,通过 `stdin.flush` 确保输入被发送到进程。然后,使用 `communicate()` 方法获取进程的输出结果,并将其写入到名为 `output.txt` 的文件中。

你可以直接执行这段代码来实现输入参数、控制进程功能,并将进程的输出结果写入到文件中。请确保 `./test` 可以正确处理输入参数并产生输出结果。如有任何疑问,请随时告诉我。

最近更新

  1. TCP协议是安全的吗?

    2024-03-22 09:20:03       18 阅读
  2. 阿里云服务器执行yum,一直下载docker-ce-stable失败

    2024-03-22 09:20:03       19 阅读
  3. 【Python教程】压缩PDF文件大小

    2024-03-22 09:20:03       18 阅读
  4. 通过文章id递归查询所有评论(xml)

    2024-03-22 09:20:03       20 阅读

热门阅读

  1. 在ubuntu22.04.4安装freeswitch1.10.10

    2024-03-22 09:20:03       17 阅读
  2. Lombok-@Singular 和 @Builder 组合

    2024-03-22 09:20:03       18 阅读
  3. 安卓利用CameraX 拍照获这张照片的exif信息

    2024-03-22 09:20:03       16 阅读
  4. php设计模式

    2024-03-22 09:20:03       18 阅读
  5. Linux常用命令(二)

    2024-03-22 09:20:03       18 阅读
  6. 页面router路由设计

    2024-03-22 09:20:03       20 阅读
  7. 自用——python代码学习(杂乱)

    2024-03-22 09:20:03       18 阅读
  8. Spring Cloud微服务Actuator和Vue

    2024-03-22 09:20:03       17 阅读
  9. 如何安装Jenkins指定版本

    2024-03-22 09:20:03       18 阅读
  10. 【非常好用的吧页面生成图片的插件html2canvas】

    2024-03-22 09:20:03       20 阅读
  11. node.js常用的命令

    2024-03-22 09:20:03       19 阅读
  12. 微信小程序 - 循环

    2024-03-22 09:20:03       22 阅读