あらきけいすけのメモ帳

あらきけいすけの雑記帳2

Python コードをファイルに生成して、生成したファイルを import する Python コード

一つのPython コードの中に「Python コードをファイルに書き出す」「その書き出した Python コードを import して、実行する」ことを書くことができた:

pyvar = 'a = (1,2,3)'
pydef = '''
def prt (x) :
  print('hello' + x)
  print(a)
  return x
'''
pydef0 = '''
class CPrint () :
  d = (1,2,3)
  def prnt (self, x) :
    print('HELLO' + x + str(self.d[1]))
    print(prt(x))
    print(a)
    return x
'''

pysrc = '[path of this file]/bb.py'
with open(pysrc,'w') as f :
  print(pyvar,file=f)
  print(pydef,file=f)
  print(pydef0,file=f)

import os
if os.path.exists(pysrc) :
  import bb
  print(bb.a)
  print(bb.prt('WORLD'))
  cc = bb.CPrint()
  print(cc.prnt('world'))