python 生成 shell 命令求教

2015 年 10 月 15 日
 okletswin
举例, 将列表中的元素组装成一条 shell 命令
['awk', '{print $1}', 'file']

要输出 awk '{print $1}' file

有没有专门的模块来做这类事的?
4221 次点击
所在节点    Python
12 条回复
cdxem713
2015 年 10 月 15 日
' '.join(['awk', '{print $1}', 'file'])
是这意思么?
okletswin
2015 年 10 月 15 日
@cdxem713 这样出来的结果是
awk {print $1} file
xvid73
2015 年 10 月 15 日
>>> ' '.join(['awk', "'{print $1}'", 'file'])
"awk '{print $1}' file"

是这个意思么?运行命令的话有 subprocess 模块。
paw
2015 年 10 月 15 日
py 里面 ' 和 " 都可以括字符串的 " ' " ' " ' 都行。。
' \' ' 转意下 也可以的
xufang
2015 年 10 月 15 日
第三方 sh 模块
cdxem713
2015 年 10 月 15 日
e
@okletswin 对不起,没看清楚,就如三楼写的那样
rundis
2015 年 10 月 16 日
import os
cmd = ' '.join(aList)
os.system(cmd)
youkeshen
2015 年 10 月 16 日
试试 Plumbum
okletswin
2015 年 10 月 16 日
@xvid73 要有办法将字符串 {print $1} 转化成 '{print $1}',字符串 awk 仍然是 awk
aec4d
2015 年 10 月 16 日
os.system(' '.join(['awk', "'{print $1}'", 'file'])) 应该可以
subprocess.Popen 有时会有 bug 遇到过
aec4d
2015 年 10 月 19 日
" ".join(pipes.quote(s) for s in strings)
okletswin
2015 年 10 月 20 日
@aec4d 正解! 非常感谢!!!

这是一个专为移动设备优化的页面(即为了让你能够在 Google 搜索结果里秒开这个页面),如果你希望参与 V2EX 社区的讨论,你可以继续到 V2EX 上打开本讨论主题的完整版本。

https://v2ex.xtra.eu.org/t/228326

V2EX 是创意工作者们的社区,是一个分享自己正在做的有趣事物、交流想法,可以遇见新朋友甚至新机会的地方。

V2EX is a community of developers, designers and creative people.

© 2021 V2EX