【问题标题】:Enter shell script variable value non-interactively using python [duplicate]使用python以非交互方式输入shell脚本变量值[重复]
【发布时间】:2013-03-11 04:30:27
【问题描述】:

Shell 脚本: 你好.sh

#!/bin/bash
echo "Enter your name: "
read name
echo "Hello $name"

我想从 python 中调用 Hello.sh 并以非交互方式填充变量“name”。怎么办?

【问题讨论】:

标签: python bash shell subprocess stdin


【解决方案1】:

你应该可以Popen.communicate子进程:

from subprocess import Popen,PIPE
p = Popen(['bash','./Hello.sh'],stdin=PIPE,stderr=PIPE,stdout=PIPE)
stdout_data,stderr_data = p.communicate("Hello World!\n")

【讨论】:

    【解决方案2】:

    pipes 上+1。一种更“shell-ish”的方法是:

    import subprocess
    
    the_name = 'the_name'
    myproc = subprocess.Popen(['echo %s | bash Hello.sh' % the_name], stdin = subprocess.PIPE, stdout = subprocess.PIPE, shell=True)
    out, err = myproc.communicate()
    
    print out
    

    【讨论】:

    • shell=True,我认为最好传递一个字符串,而不是一个列表。
    • @mgilson when shell=True: 如果 args 是字符串,该字符串指定要通过 shell 执行的命令。如果 args 是一个序列,第一项指定命令字符串,任何附加项都将被视为 shell 本身的附加参数。 所以这并不重要。
    • 感谢它按我想要的方式工作。
    猜你喜欢
    • 2014-07-16
    • 2021-08-22
    • 1970-01-01
    • 1970-01-01
    • 2016-05-29
    • 1970-01-01
    • 2011-08-24
    • 2016-02-17
    • 1970-01-01
    相关资源
    最近更新 更多