【问题标题】:Executing Interactive shell script in python在python中执行交互式shell脚本
【发布时间】:2017-02-13 18:54:17
【问题描述】:

我有一个要求用户输入的 shell 脚本。考虑下面的例子

Test.sh

#!/bin/bash
echo -n "Enter name > "
read text
echo "You entered: $text"
echo -n "Enter age > "
read text
echo "You entered: $text"
echo -n "Enter location > "
read text
echo "You entered: $text"

脚本执行:

sh test.sh
Enter name> abc
You entered: abc
Enter age > 35
You entered: 35
Enter location > prop
You entered: prop

现在我在 python 程序中调用了这个脚本。我正在使用子流程模块执行此操作。据我所知,子流程模块创建了一个新流程。问题是当我执行 python 脚本时,我无法将参数传递给底层的 shell 脚本,并且 scipt 处于 hault 阶段。可以指出我做错了什么

python 脚本(CHECK.PY):

import subprocess, shlex


cmd = "sh test.sh"
proc = subprocess.Popen(shlex.split(cmd), stdout=subprocess.PIPE, stderr=subprocess.PIPE)
stdout,stderr = proc.communicate()

print stdout

Python 执行:check.py

 python check.py

【问题讨论】:

  • 我们可以使用 OS 模块执行相同的操作,但我正在尝试使用子进程模块来实现

标签: python python-2.7 shell python-3.x


【解决方案1】:

您的代码正在运行,但是由于您提到了stdout=subprocess.PIPE,因此内容将转到您在stdout,stderr = proc.communicate() 中定义的stdout 变量。从您的 Popen() 调用中删除 stdout=subprocess.PIPE 参数,您将看到输出。

或者,您应该使用 subprocess.check_call() 作为:

subprocess.check_call(shlex.split(cmd))

【讨论】:

  • 感谢您的回答。我们如何捕获该脚本的输出?我有 python 2.6.6
  • 如果您将捕获输出,您将无法在控制台上看到脚本打印的内容。那是你要的吗?为此,您可以使用subprocess.check_output()
  • Check_output 工作正常.. 我测试过.. 但我需要使用 python 2.6.6
  • 感谢您的回答 - 有没有办法在 Jupyter 中完成这项工作。它在命令行中运行良好,但在 Jupyter 上却不行!
【解决方案2】:

实际上子进程确实有效 - 但您没有看到提示,因为子进程的标准被 proc.communicate() 捕获。您可以通过输入 3 个提示的值来确认这一点,您最终应该会看到提示并且您的输入得到回显。

只需删除stdout=subprocess.PIPE(stderr 相同),子进程的标准输出(stderr)就会进入终端。

或者有其他函数会启动一个子进程并为你调用communicate(),例如subprocess.call()subprocess.check_call()

【讨论】:

    猜你喜欢
    • 2016-05-29
    • 2011-08-31
    • 2021-07-11
    • 2010-10-10
    • 2015-12-26
    • 1970-01-01
    • 2013-06-19
    • 1970-01-01
    相关资源
    最近更新 更多