2013-02-16 9 views
5

私はparse_input.py 解析 - のpython 2.7.3

parse_input.py

のbashから、Pythonスクリプトを呼び出していますが、それには多くの '\n'文字が含まれているコマンドライン引数を取ります。

例入力:私は私がちょうど\\nなし)と同様の振る舞いを見てdata="1\n2\n"

たい`data = "1\\n2\\n"一方というPDBで見ることができる

$ python parse_input.py "1\n2\n"

import sys 
import pdb 

if __name__ == "__main__": 

    assert(len(sys.argv) == 2) 

    data = sys.argv[1] 
    pdb.set_trace() 
    print data 

\\によって置き換えられます

\を削除するには?

スクリプトで余分なものを処理したくない\ 同じ入力をファイルから受け取ることもできます。

bashのバージョン:GNUのbashのバージョン4.2.24(1)-release(i686の-pc-linux-gnuのよう)

Pythonのバージョン:2.7.3

答えて

7

Bashでは、通常のシングルクォート文字とダブルクォート文字のエスケープ文字は解釈されません。それは(いくつかの)エスケープ文字を解釈するために取得するには、$'...'使用することができます。

Words of the form $'string' are treated specially. The word expands to 
    string, with backslash-escaped characters replaced as specified by the 
    ANSI C standard. Backslash escape sequences, if present, are decoded 
    as follows: 
      \a  alert (bell) 
      \b  backspace 
      \e  an escape character 
      \f  form feed 
      \n  new line 
      \r  carriage return 
      \t  horizontal tab 
      \v  vertical tab 
      \\  backslash 
      \'  single quote 
      \nnn the eight-bit character whose value is the octal value 
       nnn (one to three digits) 
      \xHH the eight-bit character whose value is the hexadecimal 
       value HH (one or two hex digits) 
      \cx a control-x character 

    The expanded result is single-quoted, as if the dollar sign had not 
    been present. 

すなわち

$ python parse_input.py $'1\n2\n' 
+3

(+1)ニースは '$ '...''について知らなかった。 – NPE

+0

はい、常にbashについてもっと学びます。そしてzshでさらに。 – Kevin

+0

ありがとうございました! '$ '...'はトリックをしました。 – Pramod

8

バッシュはしていません解釈する\nは、Pythonのやり方では2つの文字として見えます。

あなたはstring_escapeから '解読' でのpythonでの改行リテラル\n(その2文字)を解釈することができます。

data = data.decode('string_escape') 

デモンストレーション:

>>> literal_backslash_n = '\\n' 
>>> len(literal_backslash_n) 
2 
>>> literal_backslash_n.decode('string_escape') 
'\n' 
>>> len(literal_backslash_n.decode('string_escape')) 
1 

が、他のpython string escape sequencesに注意してください。 と解釈されます。

+0

'Decode'は、どのデータ型の属性ですか?私のインタプリタの文字列で動作しません。 – asheeshr

+0

@AshRj:Python 2では 'str'(バイト文字列)です。 –

+0

これはPython 2の文字列では動作しますが、Python 3では動作しません。 – asheeshr