如何通过python子进程传递两个相同的参数?

Posted

技术标签:

【中文标题】如何通过python子进程传递两个相同的参数?【英文标题】:How to pass two same arguments via python subprocess? 【发布时间】:2016-12-16 13:05:59 【问题描述】:

我想在子进程调用中传递两个参数...像这样...

./buildbot sendchange --branch=poky --property=buildname:nice --property=machine:qemux86

所以我写了下面的程序...

# property_name = 'key': 'value'
y = ['--property=:'.format(key, value) for key, value in property_name.items()]
cmd = [
    './buildbot', 'sendchange',
    '--branch='.format(
        branch),
    y
]

上面的命令由子进程抛出错误!

Traceback (most recent call last):
  File "/home/iaskin/Workspace/latest/local/lib/python2.7/site-packages/django/core/handlers/exception.py", line 39, in inner
    response = get_response(request)
  File "/home/iaskin/Workspace/latest/local/lib/python2.7/site-packages/django/core/handlers/base.py", line 249, in _legacy_get_response
    response = self._get_response(request)
  File "/home/iaskin/Workspace/latest/local/lib/python2.7/site-packages/django/core/handlers/base.py", line 187, in _get_response
    response = self.process_exception_by_middleware(e, request)
  File "/home/iaskin/Workspace/latest/local/lib/python2.7/site-packages/channels/handler.py", line 227, in process_exception_by_middleware
    return super(AsgiHandler, self).process_exception_by_middleware(exception, request)
  File "/home/iaskin/Workspace/latest/local/lib/python2.7/site-packages/django/core/handlers/base.py", line 185, in _get_response
    response = wrapped_callback(request, *callback_args, **callback_kwargs)
  File "/home/iaskin/Workspace/latest/local/lib/python2.7/site-packages/django/contrib/auth/decorators.py", line 23, in _wrapped_view
    return view_func(request, *args, **kwargs)
  File "/home/iaskin/Workspace/buildsys/build_app/views.py", line 93, in home
    property_name=property_name
  File "/home/iaskin/Workspace/buildsys/build_app/helper/build_agent.py", line 50, in submit_buildbot
    output = subprocess.Popen(cmd, cwd=bb_master_dir)
  File "/usr/lib/python2.7/subprocess.py", line 711, in __init__
    errread, errwrite)
  File "/usr/lib/python2.7/subprocess.py", line 1343, in _execute_child
    raise child_exception
TypeError: execv() arg 2 must contain only strings

所以我把上面的代码改成了这个

y = ['--property=:'.format(key, value) for key, value in property_name.items()]
cmd = [
    './buildbot', 'sendchange', '--master=bsp-buildvm:9999',
    '--branch='.format(
        branch),
    "".format(' '.join(y))
]

这是我不想要的......

./buildbot sendchange --branch=poky "--property=buildname:nice --property=machine:qemux86"

那我做错了吗?还是subprocess 真的不允许这样做,那么还有其他选择吗?

【问题讨论】:

【参考方案1】:

在父进程中将参数保存为环境变量。子进程可以访问它。

【讨论】:

嗨...你能解释一下吗!我需要在代码中更改什么? os.environ['KEY'] = "my-personal-key" --- 这种类型的构造会设置一个环境变量。子进程可以继承这些环境变量。 设置好环境后,我该如何更改我的cmd 代码? 请您在回答中解释清楚!我没听懂你想说的..

以上是关于如何通过python子进程传递两个相同的参数?的主要内容,如果未能解决你的问题,请参考以下文章

fork() 和 wait() 有两个子进程

杀死父进程后将标准输入传递给子进程

使用 Python 子进程调用 cmd 并传递参数

python多进程和多线程

Supervisor进程管理

Python Web学习笔记之并发编程的孤儿进程与僵尸进程