subprocess.Popen shell=True to shell=False [英] subprocess.Popen shell=True to shell=False

查看:74
本文介绍了subprocess.Popen shell=True to shell=False的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I know that it is bad practice to use shell=True for subprocesses. However for this line of code, I'm not sure how to execute it with shell=False

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

我想运行的命令在哪里:

Where the command I want to run is:

candump -tA can0 can1 >> file_name

其中 file_name/path/to/file.log

推荐答案

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

You can't directly use piping in the command the way you do with shell=True, but it's easy to adapt:

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

这会在 Python 级别打开文件进行二进制追加,并将其作为子进程的 stdout 传递.

That opens the file at the Python level for binary append, and passes it as the stdout for the subprocess.

这篇关于subprocess.Popen shell=True to shell=False的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆