subprocess.Popen shell=True to shell=False

风流意气都作罢 提交于 2021-01-27 05:34:35

问题


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

Where file_name is /path/to/file.log


回答1:


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)

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




回答2:


Only shell mode supports inline piping operators so you'll need to do the redirection manually. Also, you'll need to split your command line into individual arguments which you can either do manually or have the shlex module do for you:

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


来源:https://stackoverflow.com/questions/41470965/subprocess-popen-shell-true-to-shell-false

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!