Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/python/316.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Python 为csh引用字符串_Python_Csh_Tcsh_Quoting - Fatal编程技术网

Python 为csh引用字符串

Python 为csh引用字符串,python,csh,tcsh,quoting,Python,Csh,Tcsh,Quoting,就本问题而言,我所说的“csh”是指tcsh 我知道编程时避免csh的标准建议。然而,有时需要与现有的csh代码交互,然后可能需要为csh引用一个字符串。换句话说,问题是如何用csh语法表示任意字节字符串 以下csh_escape_arg函数是否正确?也就是说,是否存在一个字符串,如果它被添加到测试中的字符串列表中,会导致该测试失败?如果存在这样一个字符串,我如何修复我的函数以使所有字符串都通过测试 import string import subprocess import unittest

就本问题而言,我所说的“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()
1) 对于tcsh,您还需要引用“=”以防止目录堆栈替换。 2) 我认为你的算法也会有一个带有未配对双引号的字符串的问题。 3) 另一种方法是以不替换字符串的方式编写目标脚本。例如,将字符串写入文件,然后让脚本将字符串从文件读入变量,如

set a = `cat file`

然后根据需要使用该变量。

谢谢。可以通过从“安全”列表中删除该字符来修复。至于不成对的双引号,你能举个例子吗?(在Python语法中)“”、““foo”和“foo”等字符串都已经通过了我问题中的测试。再想一想,似乎对代码进行了巧妙的编辑,以解决Mark Armstrong指出的“=”问题。