python 生成 shell 命令求教

2015-10-15 17:49:12 +08:00
 okletswin
举例, 将列表中的元素组装成一条 shell 命令
['awk', '{print $1}', 'file']

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

有没有专门的模块来做这类事的?
3382 次点击
所在节点    Python
12 条回复
cdxem713
2015-10-15 18:12:18 +08:00
' '.join(['awk', '{print $1}', 'file'])
是这意思么?
okletswin
2015-10-15 18:38:53 +08:00
@cdxem713 这样出来的结果是
awk {print $1} file
xvid73
2015-10-15 18:47:36 +08:00
>>> ' '.join(['awk', "'{print $1}'", 'file'])
"awk '{print $1}' file"

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

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

https://www.v2ex.com/t/228326

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

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

© 2021 V2EX