使用os.system在Python中正确处理shell转义

5

我在使用Python的os.system命令时,遇到了正确转义Shell调用的问题。我想要实现的功能类似于:

$ cat test | sort --stable -t $'\t' -k1,1

在Python环境内部,将其传递给shell。

我尝试过:

import os
cmd = "cat %s | sort --stable -t $'\\t' -k1,1" %("test")
os.system(cmd)

但是我遇到了错误:
sort: multi-character tab `$\\t'

尽管从shell中可以正常工作,但我尝试在Python中通过添加额外的斜杠来转义\t,但似乎还错过了其他内容。有什么想法可以修复这个问题吗?
谢谢。

你可以将文件名作为参数传递给sort命令,跳过cat file |这一步。祝好运。 - shellter
2个回答

5

os.system 不会像你期望的那样在普通的 bash 环境下执行命令。你可以通过直接调用 bash 来解决这个问题:

import os
cmd = """/bin/bash -c "cat %s | sort --stable -t $'\t' -k1,1" """ % "test"
os.system(cmd)

但是你需要注意,os.system已被标记为过时的,并将在未来的Python版本中被移除。你可以使用subprocess的便捷方法call来模仿os.system的行为以保证你的代码具有未来性:

import subprocess
cmd = """/bin/bash -c "cat %s | sort --stable -t $'\t' -k1,1" """ % "test"
subprocess.call(cmd, shell=True)

如果您感兴趣,使用subprocess模块调用命令还有更多方法:

http://docs.python.org/library/subprocess.html#module-subprocess


1

首先,您应该避免无用的cat使用:http://google.com/search?q=uuoc

其次,您确定您的sort命令不理解反斜杠-t吗?这应该可以解决:

sort --stable -t'\t' -k1,1 test

它也应该可以从Python中正常工作:

os.system("sort --stable -t'\\t' -k1,1 test")
# or
os.system(r"sort --stable -t'\t' -k1,1 test")

最后,如果您切换到subprocess(建议使用),请避免使用shell=True
subprocess.call(["sort", "--stable", "-t\t", "-k1,1", "test"])

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接