简体   繁体   English

如何通过subprocess.arg中的arg将'env'var传递给Python脚本

[英]How to pass 'env' var to a Python script via an arg in subprocess.Popen

I am writing an Python wrapper where a Python script creates a custom env variable by adding a large number of elements. 我正在编写一个Python包装器,其中Python脚本通过添加大量元素来创建自定义env变量。

For example: 例如:

env['DEBUG'] = '1'
env['TBB_NUM_THREADS'] = str(args.threads)
...

This first wrapper calls a second wrapper via subprocess.Popen like this: 第一个包装器通过subprocess.Popen调用第二个包装器,如下所示:

command = ['wrapper2.py'] + args
subprocess.Popen(command, env=env).wait()

I need the second wrapper to have the same env as the first. 我需要第二个包装器具有与第一个包装器相同的环境。 Ideally, I would like to modify the above assignment so the second argument is the env. 理想情况下,我想修改上述分配,以便第二个参数是env。 In this way the second script can easily access it and set its env to that of the first script. 这样,第二个脚本可以轻松访问它并将其env设置为第一个脚本的env。

command = ['wrapper2.py'] + env + args

But this causes the following error: "Typeerror: can only concatenate list (not "instance") to list" 但这会导致以下错误:“ Typeerror:只能将列表(而不是“实例”)连接到列表”

What would be the best way to approach this problem? 解决这个问题的最佳方法是什么? Note: I am using Python 2.7 注意:我正在使用Python 2.7

It's an ugly hack, but if you're unwilling to pass env out-of-band from args as a separate argument, you can use the env UNIX utility to set your environment variables instead of using the subprocess env facility. 这是一个丑陋的技巧,但是如果您不愿意将args env带外作为单独的参数传递,则可以使用env UNIX实用程序来设置环境变量,而不是使用subprocess env工具。

That is: 那是:

args = [ 'env', 'DEBUG=1', 'TBB_NUM_THREADS=%s' % (arg_threads),
         './wrapper2.py' ] + wrapper2_args

A less-ugly hack is to pass around a single kwargs list that contains both: 一个不太丑陋的技巧是传递包含以下两个参数的单个kwargs列表:

kwargs = {
  'args': [ './wrapper2.py' ] + wrapper2_args,
  'env':  { "DEBUG": "1", "TBB_NUM_THREADS": str(arg_threads), }
}

...and then pass it in using **kwargs syntax: ...然后使用**kwargs语法将其传递:

p = subprocess.Popen(**kwargs)

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

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