简体   繁体   English

与python文件上的execfile / subprocess.call中的对象进行交互

[英]interacting with objects in execfile/subprocess.call on python file with arguments

Python novice here. Python新手在这里。

I am trying to interact with the variables/objects in a python file that requires arguments for its data. 我正在尝试与需要数据参数的python文件中的变量/对象进行交互。 Let's say I can only get this data from arguments , rather than make a script that includes arguments that would be passed (which means I must use execfile or subprocess.call). 假设我只能从arguments中获取此数据 ,而不是创建一个包含将要传递的参数的脚本(这意味着我必须使用execfile或subprocess.call)。

Let's say this was my python file, foo.py: 假设这是我的python文件foo.py:

bar = 123
print("ran foo.py, bar = %d" % bar)

Of course, there would be more to the file to parse arguments, but that is irrelevant. 当然,文件中还有更多的参数可以解析,但这是无关紧要的。

Now, in a python shell (either python or ipython in a terminal): 现在,在python shell中(终端中的python或ipython):

>>> import subprocess
>>> subprocess.call("python foo.py 'args'", shell=True)
ran foo.py, bar = 123
0
>>> bar
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
NameError: name 'bar' is not defined

As the example output above shows, bar is not defined after stdout from foo.py. 如上面的示例输出所示,在foo.py的stdout之后未定义bar。

Is there any way to interact with variables or data objects in a python file called by execfile or subprocess.call? 有什么方法可以与execfile或subprocess.call调用的python文件中的变量或数据对象进行交互? Normally I would eval in a REPL or run in an IDE so I can test out values and objects after execution, but I cannot figure out how to do this with a python file that builds data from parsed arguments. 通常,我将在REPL中评估或在IDE中运行,以便在执行后可以测试值和对象,但是我无法弄清楚如何使用从解析的参数构建数据的python文件来执行此操作。

Does anyone know how I can do this? 有人知道我该怎么做吗? Thanks for your consideration, at any rate. 非常感谢您的考虑。

Is foo.py under your control? foo.py是否在您的控制之下? If yes, simply change it, such that it can be run by being imported as module and interacted with. 如果是,只需对其进行更改,以便可以通过将其作为模块导入并与之交互来运行。 If no, you may need to catch the output as string and newly build your variable bar from it. 如果否,则可能需要将输出捕获为字符串,并从中重新构建变量bar How you capture the output of a subprocess is answered here for example: Running shell command from Python and capturing the output 例如,这里回答了如何捕获子进程的输出: 从Python运行shell命令并捕获输出

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM