2014-06-20 112 views
1

我一直在嘗試使用linux shell將一串字節輸出到使用Python的文件中。問題是當我這樣做時:Python中奇怪的換行符錯誤

python -c "print '\x11\x22\x33\x44'" > new_file 

new_file包含'\ x11 \ x22 \ x33 \ x44 \ x0a'。

我在這裏擡頭類似的問題在計算器上,並試圖通過以下及其他許多類似的技術來剝離出\ X0A:

python -c "print '\x11\x22\x33\x44'.rstrip('\x0a')" > new_file 

的\ X0A,但拒絕去。

有沒有人遇到過這個問題?真的很感謝快速解決。謝謝。 PS:我已經嘗試過使用各種版本的Python,包括2.5,2.7,3.1,3.3。所有導致同樣的問題。

回答

1

這是因爲print函數在最後自動添加換行符(ascii 0x0a)。您可以使用Python 3版本的print設置結束字符:

> python3 -c "print('\x11\x22\x33\x44', end='')" > new_file 
> hexdump -C new_file 
11 22 33 44 

如果你確實需要使用Python 2,你可以使用this trick運行在終端多行Python代碼:

echo -e "import sys\nsys.stdout.write('\x11\x22\x33\x44')" | python > new_file 
+2

甚至更​​少的字符:'python -c「import sys; sys.stdout.write('\ x11 \ x22 \ x33 \ x44')」> new_file' – bgporter

+0

Thanks guys。這工作完美。只是想知道,爲什麼'打印'一個0x0a但stdout.write不?是否因爲打印函數假定它的參數是字符串? – user904832