ThaiTux.info - etc https://www.thaitux.info/taxonomy/term/183 python: คำสั่ง exec https://www.thaitux.info/node/185 <div class="field field-name-body field-type-text-with-summary field-label-hidden"><div class="field-items"><div class="field-item even"><p>Python มีคำสั่ง exec ที่ใช้ในการแทนค่าตัวแปรแล้วรันคำสั่งแบบพลวัต (dynamicly)<br /> บันทึกพฤติกรรมของ exec ไว้ดังนี้</p> <dl> <dt>การใช้งาน</dt> <dd> <pre>&gt;&gt;&gt; var='123' &gt;&gt;&gt; a='print %s' % (var) &gt;&gt;&gt; exec a # OR exec(a) 123</pre></dd> <dt>การกำหนดตัวแปร var ใหม่ ไม่สามารถเปลี่ยนแปลงการแทนค่าจากครั้งก่อน ต้องกำหนดใหม่ทั้งสองครั้ง</dt> <dd> <pre>&gt;&gt;&gt; var=456 &gt;&gt;&gt; exec a 123 &gt;&gt;&gt; a='print %s' % (var) &gt;&gt;&gt; exec a 456 </pre></dd> <dt>การแทนค่า ไพธอนจะแทนค่าทุกสิ่งทุกอย่างของตัวแปร ลงไปในคำสั่ง<br /> เวลาใช้กับตัวแปร string ต้องใส่เครื่องหมาย quot ซ้อนด้วย</dt> <dd> <pre>&gt;&gt;&gt; var='abc' &gt;&gt;&gt; a='print %s' % (var) &gt;&gt;&gt; exec a Traceback (most recent call last): File "&lt;stdin&gt;", line 1, in ? File "&lt;string&gt;", line 1, in ? NameError: name 'abc' is not defined &gt;&gt;&gt; <strong>var='"abc"'</strong> &gt;&gt;&gt; a='print %s' % (var) &gt;&gt;&gt; exec a abc</pre><p>ยกเว้นกรณีคำสั่ง import ต้องใช้แบบปกติ</p> <pre>&gt;&gt;&gt; var='re' &gt;&gt;&gt; a='import %s' % (var) &gt;&gt;&gt; exec a &gt;&gt;&gt; dir(re) ['DOTALL', 'I', 'IGNORECASE', 'L', 'LOCALE', 'M', 'MULTILINE', 'S', 'U', 'UNICODE', 'VERBOSE', 'X', '__all__', '__builtins__', '__doc__', '__file__', '__name__', 'compile', 'engine', 'error', 'escape', 'findall', 'finditer', 'match', 'purge', 'search', 'split', 'sub', 'subn', 'template']</pre></dd> </dl> <dt> </dt></div></div></div><div class="field field-name-taxonomy-vocabulary-1 field-type-taxonomy-term-reference field-label-above"><div class="field-label">Topic:&nbsp;</div><div class="field-items"><div class="field-item even"><a href="/taxonomy/term/7">python</a></div><div class="field-item odd"><a href="/taxonomy/term/183">etc</a></div></div></div> Fri, 02 Feb 2007 01:28:33 +0000 wd 185 at https://www.thaitux.info https://www.thaitux.info/node/185#comments python: เกร็ดความรู้ของภาษา https://www.thaitux.info/node/184 <div class="field field-name-body field-type-text-with-summary field-label-hidden"><div class="field-items"><div class="field-item even"><p>รวบรวมเกร็ดการทดลอง นำมาเขียนไว้กันลืม</p> <p>ที่เหลือ พยายามเขียนลงไว้ใน <a href="/py/spb.py">Python Book</a> แทน เพื่อเอาไว้อ้างอิง</p> </div></div></div><div class="field field-name-taxonomy-vocabulary-1 field-type-taxonomy-term-reference field-label-above"><div class="field-label">Topic:&nbsp;</div><div class="field-items"><div class="field-item even"><a href="/taxonomy/term/7">python</a></div><div class="field-item odd"><a href="/taxonomy/term/183">etc</a></div></div></div> Fri, 02 Feb 2007 01:17:45 +0000 wd 184 at https://www.thaitux.info https://www.thaitux.info/node/184#comments