就这个问题而言,“csh”是指 tcsh。
我知道避免使用 csh 进行编程的标准建议。但是,有时需要与现有的 csh 代码交互,然后可能需要为 csh 引用一个字符串。换句话说,问题是如何在 csh 语法中表示任意字节字符串。
以下 csh_escape_arg 函数是否正确?也就是说,是否存在一个字符串,如果将其添加到测试中的字符串列表中,会导致该测试失败?如果有这样的字符串,我该如何修复我的函数以使所有字符串都通过测试?
import string
import subprocess
import unittest
# Safe unquoted
_safechars = frozenset(string.ascii_letters + string.digits + '@%_-+:,./')
def csh_escape_arg(str_):
"""Return a representation of str_ in csh.
Based on the standard library's pipes.quote
"""
for c in str_:
if c not in _safechars:
break
else:
if not str_:
return "''"
return str_
str_ = str_.replace("\\", "\\\\")
str_ = str_.replace("\n", "\\\n")
str_ = str_.replace("!", "\\!")
# use single quotes, and put single quotes into double quotes
# the string $'b is then quoted as '$'"'"'b'
return "'" + str_.replace("'", "'\"'\"'") + "'"
def csh_escape(args):
return " ".join(csh_escape_arg(arg) for arg in args)
def get_cmd_stdout(args, **kwargs):
child = subprocess.Popen(args, stdout=subprocess.PIPE, **kwargs)
stdout, stderr = child.communicate()
rc = child.returncode
if rc != 0:
raise Exception("Command failed with return code %d: %s:\n%s" % (rc, args, stderr))
else:
return stdout
class TestCsh(unittest.TestCase):
def test_hard_cases(self):
for angry_string in [
"\\!\n\"'`",
"\\\\!\n\"'`",
"=0",
]:
out = get_cmd_stdout(["tcsh", "-c", csh_escape(["echo", "-n", angry_string])])
self.assertEqual(out, angry_string)
unittest.main()