【问题标题】:How to pass arguments to subprocess如何将参数传递给子进程
【发布时间】:2018-09-17 06:18:04
【问题描述】:

我想通过 python 脚本在 gnome-terminal 中运行一个名为 client.sh 的进程,并希望将参数作为输入传递以执行它。下面是我的代码

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”发送到 client.sh 进程。 但是使用上面的代码,我的 process[client.sh] 没有得到任何输入。 如何将输入发送到我的子流程?

【问题讨论】:

  • 有什么问题?
  • 如果您不解释问题所在,那么没有理由不将这个问题作为 3000 个其他“我如何启动子流程”问题的副本来关闭。关心更具体吗?您发布的代码有什么问题?
  • 我想向进程发送输入。 itried process.communicate 如上所述。但它没有工作。

标签: python subprocess


【解决方案1】:

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

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

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

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

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

然后:

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

【讨论】:

  • 按照你的建议我累了。如果我让 shell = False process = subprocess.Popen(['sudo gnome-terminal -x ./client.sh','1'], stdin=PIPE, stdout=PIPE, stderr=PIPE, shell= 得到以下错误错误)文件“/root/anaconda2/lib/python2.7/subprocess.py”,第 390 行,在 init errread, errwrite)文件“/root/anaconda2/lib/python2.7/subprocess .py", line 1025, in _execute_child raise child_exception OSError: [Errno 2] No such file or directory
  • 查看我的编辑。另外,尝试使用完整路径,即:/home/foo/client.sh
猜你喜欢
  • 1970-01-01
  • 2012-05-27
  • 1970-01-01
  • 2018-03-16
  • 1970-01-01
  • 1970-01-01
  • 2023-03-03
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多