0

我需要从另一个脚本调用一个 python 脚本,我试图在 execfile 函数的帮助下完成它。我需要将字典作为参数传递给调用函数。有没有可能这样做?

import subprocess
from subprocess import Popen
-------To read the data from xls----- 
ret_lst = T_read("LDW_App05")

for each in ret_lst:
    lst.append(each.replace(' ','-'))
    lst.append(' ')


result = Popen(['python','LDW_App05.py'] + lst ,stdin = subprocess.PIPE,stdout = subprocess.PIPE).communicate()
print result

在这里,在上面的代码中,我以列表的形式从 Excel 工作表中读取输入数据,我需要将列表作为参数传递给 LDW_App05.py 文件

4

1 回答 1

2

我建议不要将复杂数据作为 CL 参数传递,而是通过 STDIN/STDOUT 管道传输您的数据 - 这样您就不必担心转义特殊的、shell 有效的字符并超过最大命令行长度。

通常,作为基于 CL 参数的脚本,您可能具有以下内容app.py

import sys

if __name__ == "__main__":  # ensure the script is run directly
    if len(sys.argv) > 1:  # if at least one CL argument was provided 
        print("ARG_DATA: {}".format(sys.argv[1]))  # print it out...
    else:
        print("usage: python {} ARG_DATA".format(__file__))

它显然希望传递一个参数,如果从另一个脚本传递,它将打印出来,比如caller.py

import subprocess

out = subprocess.check_output(["python", "app.py", "foo bar"])  # pass foo bar to the app
print(out.rstrip())  # print out the response
# ARG_DATA: foo bar

但是如果你想传递一些更复杂的东西,比如说 adict呢?由于 adict是一个层次结构,我们需要一种方法来将它呈现在一行中。有很多格式可以满足要求,但让我们坚持使用基本的 JSON,因此您可能会将您的caller.py设置设置为如下所示:

import json
import subprocess

data = {  # our complex data
    "user": {
        "first_name": "foo",
        "last_name": "bar",
    }
}
serialized = json.dumps(data)  # serialize it to JSON
out = subprocess.check_output(["python", "app.py", serialized])  # pass the serialized data
print(out.rstrip())  # print out the response
# ARG_DATA: {"user": {"first_name": "foo", "last_name": "bar"}}

现在,如果您修改您app.py以识别它接收 JSON 作为参数的事实,您可以将其反序列化回 Pythondict以访问其结构:

import json
import sys

if __name__ == "__main__":  # ensure the script is run directly
    if len(sys.argv) > 1:
        data = json.loads(sys.argv[1])  # parse the JSON from the first argument
        print("First name: {}".format(data["user"]["first_name"]))
        print("Last name: {}".format(data["user"]["last_name"]))
    else:
        print("usage: python {} JSON".format(__file__))

然后,如果你caller.py再次运行你的,你会得到:

名字:傅
姓名:酒吧

但这非常乏味,而且 JSON 对 CL 不是很友好(在幕后 Python 进行了大量的转义以使其工作)更不用说你的 JSON 可以传递的大小有限制(取决于操作系统和 shell)这边走。使用 STDIN/STDOUT 缓冲区在进程之间传递复杂数据要好得多。为此,您必须修改您的app.py以等待其 STDIN 上的输入,并向caller.py其发送序列化数据。所以,app.py可以很简单:

import json

if __name__ == "__main__":  # ensure the script is run directly
    try:
        arg = raw_input()  # get input from STDIN (Python 2.x)
    except NameError:
        arg = input()  # get input from STDIN (Python 3.x)
    data = json.loads(arg)  # parse the JSON from the first argument
    print("First name: {}".format(data["user"]["first_name"]))  # print to STDOUT
    print("Last name: {}".format(data["user"]["last_name"]))  # print to STDOUT

caller.py

import json
import subprocess

data = {  # our complex data
    "user": {
        "first_name": "foo",
        "last_name": "bar",
    }
}

# start the process and pipe its STDIN and STDOUT to this process handle:
proc = subprocess.Popen(["python", "app.py"], stdin=subprocess.PIPE, stdout=subprocess.PIPE)
serialized = json.dumps(data)  # serialize data to JSON
out, err = proc.communicate(serialized)  # send the serialized data to proc's STDIN
print(out.rstrip())  # print what was returned on STDOUT

如果caller.py你再次调用你得到:

名字:傅
姓名:酒吧

但是这次你传递给你的数据大小没有限制,app.py你不必担心在 shell 转义过程中某种格式是否会被弄乱等。你也可以保持“通道”打开并拥有两个进程以双向方式相互通信 - 请查看此答案以获取示例。

于 2017-07-19T12:35:27.087 回答