子流程.Popenshell=对shell=Fals

2024-06-23 18:33:31 发布

您现在位置:Python中文网/ 问答频道 /正文

我知道在子进程中使用shell=True是不好的做法。但是对于这一行代码,我不确定如何在shell=False的情况下执行它

subprocess.Popen('candump -tA can0 can1 >> %s' %(file_name), shell=True)

我要运行的命令是:

^{pr2}$

其中file_name/path/to/file.log


Tags: 代码name命令falsetrue进程情况shell
2条回答

只有shell模式支持内联管道操作符,因此需要手动执行重定向。此外,您还需要将命令行拆分为单独的参数,您可以手动执行这些操作,也可以让shlex模块为您执行这些操作:

subprocess.Popen(shlex.split('candump -tA can0 can1'), stdout=open(file_name, 'ab'))

不能像使用shell=True那样在命令中直接使用管道,但它很容易适应:

with open(file_name, 'ab') as outf:
    proc = subprocess.Popen(['candump', '-tA', 'can0', 'can1'], stdout=outf)

它在Python级别为binary append打开文件,并将其作为子进程的stdout传递。在

相关问题 更多 >

    热门问题