subprocess.Popen shell = True to shell = False

ave*_*udi 5 python shell subprocess

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

subprocess.Popen('candump -tA can0 can1 >> %s' %(file_name), shell=True)
Run Code Online (Sandbox Code Playgroud)

我想要运行的命令是:

candump -tA can0 can1 >> file_name
Run Code Online (Sandbox Code Playgroud)

哪里file_name/path/to/file.log

Sha*_*ger 8

您无法像执行命令那样在命令中直接使用管道shell=True,但它很容易适应:

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

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

  • @avelampudi`a`ppend`b'inary. (2认同)