如何将参数传递给子进程

2024-03-29 12:18:20 发布

您现在位置:Python中文网/ 问答频道 /正文

我要运行一个名为客户端.sh在gnome终端中通过python脚本,并希望传递参数作为输入来执行它。下面是我的代码

import os
import subprocess
import time
from subprocess import Popen,PIPE
import pexpect
process = subprocess.Popen('sudo gnome-terminal  -x ./client.sh', stdin=PIPE, stdout=PIPE, stderr=PIPE, shell=True)
process.communicate(input = "1") 

我的意图是将输入作为“1”发送到客户端.sh过程。 但用上面的代码我的程序[客户端.sh]没有得到任何输入。 如何将输入发送到子流程?。在


Tags: 代码fromimport脚本终端客户端参数time
1条回答
网友
1楼 · 发布于 2024-03-29 12:18:20

您可以使用以下参数调用命令:

process = subprocess.Popen(['sudo gnome-terminal  -x ./client.sh', '1'], stdin=PIPE, stdout=PIPE, stderr=PIPE, shell=False)

使用shell=True时要小心,请参见this。在

如果需要“模拟”参数输入,请使用:

^{pr2}$

然后:

process.stdin.write("1" + "\n")

相关问题 更多 >