2013-04-05 15 views
4

我現在有Python的-c開關

".".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開關失敗?

[[email protected] ~]# 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' 

任何想法?

+1

轉義的雙引號雙引號內.. – 2013-04-05 13:35:20

回答

6

看起來像命令行上的引用問題。

嘗試用單引號包裝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解釋器,因此您需要明確地打印結果。

+0

他的Python代碼中也有單引號。 – Cairnarvon 2013-04-05 13:34:20

+0

@Cairnarvon是的,但是可以將它們改爲雙引號,除非它們用於嵌套它們看起來不像的東西,否則Python中沒有區別。嘗試該方法時仍然存在問題 – unwind 2013-04-05 13:35:06

+0

:-( – felix001 2013-04-05 13:49:46

4

在引用的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,這方法仍然可以用來捕獲腳本到一個變量定界符文本中受益:

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"