简体   繁体   English

如何使用python子进程正确控制命令行程序?

[英]How to use python subprocess to control command line program correctly?

I have an external command line program I'd like to control via python. 我有一个想通过python控制的外部命令行程序。 When using subprocess.open it continuously prints the first command in the terminal. 使用subprocess.open时,它将连续在终端中打印第一个命令。 I want to input a series of commands one after another and then terminate the program once it has finished running. 我要一个接一个地输入一系列命令,然后在程序运行完毕后终止它。 I've tried several different method, but nothing seems to work. 我尝试了几种不同的方法,但似乎没有任何效果。 Can someone show me what I'm doing wrong, or help me fix my code? 有人可以告诉我我在做什么错,还是可以帮助我修复代码? This is what I have: 这就是我所拥有的:

from subprocess import Popen, PIPE
program_location = /Fortran/Program/Here/Program

file_location = /Place/For/Input/File/File.EXP
command_list = [file_location, 'expedt', 'y', 'y', 'x', 'powpref', 'genles']
p = Popen(program_location, stdin=PIPE)

for i in command_list:
    ps.stdin.write(i)

使用Popen.communicate将输入行发送到进程并等待它完成。

If you want all commands to run in parallel, you can run subprocess.call with the help of multiprocessing. 如果希望所有命令并行运行,则可以在多重处理的帮助下运行subprocess.call。

import subprocess
import multiprocessing

cmd_1 = ["timeout", "15", "ping", "google.com"]
cmd_2 = ["timeout", "15", "ping", "stackoverflow.com"]

cmds = [cmd_1, cmd_2]

for i in range(len(cmds)):
    p = multiprocessing.Process(target=subprocess.call, args=(cmds[i],))
    p.start()

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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