2024-06-23 18:33:31 发布
网友
我知道在子进程中使用shell=True是不好的做法。但是对于这一行代码,我不确定如何在shell=False的情况下执行它
subprocess.Popen('candump -tA can0 can1 >> %s' %(file_name), shell=True)
我要运行的命令是:
其中file_name是/path/to/file.log
file_name
/path/to/file.log
只有shell模式支持内联管道操作符,因此需要手动执行重定向。此外,您还需要将命令行拆分为单独的参数,您可以手动执行这些操作,也可以让shlex模块为您执行这些操作:
subprocess.Popen(shlex.split('candump -tA can0 can1'), stdout=open(file_name, 'ab'))
不能像使用shell=True那样在命令中直接使用管道,但它很容易适应:
shell=True
with open(file_name, 'ab') as outf: proc = subprocess.Popen(['candump', '-tA', 'can0', 'can1'], stdout=outf)
它在Python级别为binary append打开文件,并将其作为子进程的stdout传递。在
stdout
只有shell模式支持内联管道操作符,因此需要手动执行重定向。此外,您还需要将命令行拆分为单独的参数,您可以手动执行这些操作,也可以让shlex模块为您执行这些操作:
不能像使用
shell=True
那样在命令中直接使用管道,但它很容易适应:它在Python级别为binary append打开文件,并将其作为子进程的
stdout
传递。在相关问题 更多 >
编程相关推荐