Python 2.7中含find的subprocess命令执行失败求助
问题分析与解决办法
嘿,我来帮你排查这个subprocess命令失败的原因~
错误根源
你这里犯了一个典型的subprocess使用误区:当设置shell=True时,不需要对命令字符串调用.split()。
当shell=True时,subprocess会把整个命令字符串交给系统shell(比如bash)去完整解析执行。但你用.split()把命令拆成了列表['for', 'f', 'in', '$(find', '_test/', '-name', '*.c', '-print);', 'do', 'echo', 'hello;', 'done'],这就导致shell收到的第一个参数是for——而for是shell的关键字,不是可执行命令,自然会抛出语法错误。
修复方案
有两种靠谱的解决方式:
方案1:直接传递完整命令字符串(保留shell=True)
去掉.split(),直接把完整的shell命令作为字符串传给subprocess.call:
import subprocess subprocess.call("for f in $(find _test/ -name *.c -print); do echo hello; done", shell=True)
方案2:用Python原生逻辑替代shell命令(更安全推荐)
尽量避免shell=True(它存在shell注入的安全风险,而且跨平台性差),可以用Python自带的模块实现相同的逻辑:
import os # 遍历_test目录下所有.c文件 for root, dirs, files in os.walk('_test'): for file in files: if file.endswith('.c'): print("hello")
如果你的Python 2.7版本支持glob的递归查找(需要Python 2.7.13+),也可以这么写:
import glob for f in glob.glob('_test/**/*.c', recursive=True): print("hello")
内容的提问来源于stack exchange,提问作者zell
相关产品推荐
相关产品推荐

