如何通过Python执行任意的shell脚本并传递多个变量?

2024-04-26 11:13:29 发布

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

我正在用Python构建一个应用程序插件,它允许用户用简单的脚本任意扩展应用程序(在macosx下工作)。执行Python脚本很容易,但是有些用户对Ruby这样的语言比较熟悉。在

从我所读到的,我可以使用subprocess轻松地执行Ruby脚本(或其他任意shell脚本),并用管道捕获它们的输出;这不是问题,网上有很多例子。但是,我需要为脚本提供多个变量(比如一个文本块以及一些关于脚本正在修改的文本的简单布尔信息),我很难找到实现这一点的最佳方法。在

有没有人建议最好的方法来实现这一点?我的目标是用最少的代码为脚本提供所需的信息。在

提前谢谢!在


Tags: 方法用户文本脚本插件语言信息应用程序
3条回答

如果要启动多个脚本,并且需要向每个脚本传递相同的信息,则可以考虑使用该环境(警告,我不知道Python,因此以下代码很可能很糟糕):

#!/usr/bin/python 

import os

try:
    #if environment is set
    if os.environ["child"] == "1":
        print os.environ["string"]
except:
    #set environment
    os.environ["child"]  = "1"
    os.environ["string"] = "hello world"

    #run this program 5 times as a child process
    for n in range(1, 5):
        os.system(__file__)

http://docs.python.org/library/subprocess.html#using-the-subprocess-module

args should be a string, or a sequence of program arguments. The program to execute is normally the first item in the args sequence or the string if a string is given, but can be explicitly set by using the executable argument.

所以,你的电话可能是这样的

p = subprocess.Popen( args=["script.sh", "-p", p_opt, "-v", v_opt, arg1, arg2] )

您已经将任意Python值放入subprocess.Popen的参数中。在

您可以采取的一种方法是使用json作为父脚本和子脚本之间的协议,因为json支持在许多语言中都很容易获得,并且具有相当的表达能力。您还可以使用管道将任意数量的数据发送到子进程,前提是您的要求允许您从标准输入中读取子脚本。例如,父对象可以执行如下操作(显示的是python2.6):

#!/usr/bin/env python

import json
import subprocess

data_for_child = {
    'text' : 'Twas brillig...',
    'flag1' : False,
    'flag2' : True
}

child = subprocess.Popen(["./childscript"], stdin=subprocess.PIPE)
json.dump(data_for_child, child.stdin)

下面是一个儿童剧本的草图:

^{pr2}$

在这个简单的例子中,输出是:

$ ./foo12.py
{u'text': u'Twas brillig...', u'flag2': True, u'flag1': False}

相关问题 更多 >