Python-c开关

2024-05-28 23:12:53 发布

您现在位置:Python中文网/ 问答频道 /正文

我现在有

".".join(str(z) for z in [int(x, 16) for x in (re.sub(r'(.{2})(?!$)', r'\1.', "00112233")).split('.')])
'xx.xx.xx.xx'

哪种方法有效,但当我试图通过python-c开关使用它时失败了?

[root@monty ~]# python -c "import re ; ".".join(str(z) for z in [int(x, 16) for x in (re.sub(r'(.{2})(?!$)', r'\1.', "00112233")).split('.')])"
python -c "import re ; ".".join(str(z) for z in [int(x, 16) for x in (re.sub(r'(.{2})(?"import re ; ".".join(str(z) for z in [int(x, 16) for x in (re.sub(r'(.{2})(?python)', r'\1.', "00112233")).split('.')])")', r'\1.', "00112233")).split('.')])"
-bash: syntax error near unexpected token `str'

有什么想法吗?


Tags: 方法inimportrebashforerrorroot
2条回答

在引用的heredoc上输入脚本,而不是使用python -c,这样问题就完全没有意义了;而且,这样可以在代码中使用换行符,因此可读性更强。

python - <<'EOF'
import re
print ".".join(str(z) for z in [int(x, 16)
                                for x in (re.sub(r'(.{2})(?!$)',
                                          r'\1.',
                                          "00112233")).split('.')])
EOF

注意,在这里使用<<'EOF'而不是<<EOF是很重要的;前者防止shell试图扩展heredoc的内容。


如果您真的想使用python -c,这个方法仍然可以从用于将脚本捕获到变量的heredoc中获益:

python_script=$(cat <<'EOF'
import re
print ".".join(str(z) for z in [int(x, 16)
                                for x in (re.sub(r'(.{2})(?!$)',
                                          r'\1.',
                                          "00112233")).split('.')])
EOF
)

python -c "$python_script"

在命令行上看起来像是引用问题。

尝试将Python字符串包装成单引号,而不要在其中使用单引号。

您还可以使用\"转义与shell解释冲突的引号。

$ python -c 'import re;print ".".join(str(z) for z in [int(x, 16) for x in (re.sub(r"(.{2})(?!$)", r"\1.", "00112233")).split(".")])'
0.17.34.51

注意:由于不再运行python解释程序,因此需要显式地打印结果。

相关问题 更多 >

    热门问题