问题描述
我需要从另一个脚本中调用一个python脚本,我试图在execfile函数的帮助下进行操作.我需要将字典作为参数传递给调用函数.是否有可能这样做?
I need to call one python script from another script,I'm trying to do it with the help of execfile function.I need to pass a dictionary as an argument to the calling function.Is there any possibility to do that?
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文件
Here,in the above code I'm reading the Input data from the Excel sheet in the form of list,I need to pass the list as an argument to LDW_App05.py file
推荐答案
我建议通过STDIN/STDOUT传递数据,而不是将复杂的数据作为CL参数传递,那么您不必担心转义特殊的shell -重要字符,超过了最大命令行长度.
Instead of passing complex data as CL arguments, I propose piping your data via the STDIN/STDOUT - then you don't need to worry about escaping special, shell-significant chars and exceeding the maximum command line length.
通常,作为基于CL参数的脚本,您可能会有类似app.py
的内容:
Typically, as CL argument-based script you might have something like 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
:
It clearly expects an argument to be passed and it will print it out if passed from another script, say 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
但是,如果您想传递更复杂的内容,例如dict
,该怎么办?由于dict
是分层结构,因此我们需要一种将其显示在一行中的方法.有很多格式可以满足要求,但让我们坚持使用基本的JSON,因此您可以将caller.py
设置为以下格式:
But what if you want to pass something more complex, let's say a dict
? Since a dict
is a hierarchical structure we'll need a way to present it in a single line. There are a lot of formats that would fit the bill, but let's stick to the basic JSON, so you might have your caller.py
set to something like this:
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作为参数的事实,则可以将其反序列化回Python dict
以访问其结构:
Now if you modify your app.py
to recognize the fact that it's receiving JSON as an argument you can deserialize it back to Python dict
to access its structure:
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
,则会得到:
Then if you run your caller.py
again you'll get:
First name: foo
Last name: bar
但是这非常繁琐,并且JSON对CL不太友好(在后台Python进行了大量的转义以使其起作用),更不用说JSON的大小是有限制的(取决于操作系统和外壳程序)可以通过这种方式传递.最好使用STDIN/STDOUT缓冲区在进程之间传递复杂的数据.为此,您必须修改app.py
以等待其STDIN上的输入,并让caller.py
向其发送序列化数据.因此,app.py
可以很简单:
But this is very tedious and JSON is not very friendly to the CL (behind the scenes Python does a ton of escaping to make it work) not to mention there is a limit (OS and shell depending) on how big your JSON can be passed this way. It's much better to use STDIN/STDOUT buffer to pass your complex data between processes. To do so, you'll have to modify your app.py
to wait for input on its STDIN, and for caller.py
to send serialized data to it. So, app.py
can be as simple as:
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
,您将再次得到:
and if you invoke caller.py
you again get:
First name: foo
Last name: bar
但是这一次您传递给app.py
的数据大小没有限制,您不必担心在转义shell期间是否会弄乱某种格式.您还可以保留渠道"处于开放状态,并使两个进程以双向方式相互通信-请查看此答案作为示例.
But this time there is no limit to the data size you're passing over to your app.py
and you don't have to worry if a certain format would be messed up during shell escaping etc. You can also keep the 'channel' open and have both processes communicate with each other in a bi-directional fashion - check this answer for an example.
这篇关于在python 2.7中将参数传递给execfile的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!