0

Would the most efficient way-and I know it's not very efficient, but I honestly can't find any better way-to manipulate a Python (.py) file, to add/subtract/append code, be to use the basic file I/O module included in Python?

For an example:

obj = open('Codemanipulationtest.py', 'w+')
obj.write("print 'This shows you can do basic I/O?'")
obj.close()

Will manipulate a file I have, named "codemanipulationtest.py", and add to it a print statement. Is this something that can be worked upon or are there any easier or more safe/efficient methods for manipulating/creating new python code?

I've read over this: Parse a .py file, read the AST, modify it, then write back the modified source code

And honestly it seems like the I/O method is easier. I am kind of newbish to Python so I may just be acting stupid.....thanks in advance for any responses.

Edit

The point of it all was simply to play around with the effects playing around with the code. I was thinking of hooking up whatever I end up using to some sort of learning algorithm and seeing how well it could generate little bits of code at a time, and seeing where it could go from there....

4

2 に答える 2

1

コードを生成するには、コードをさまざまなクラス、IF クラス、FOR クラスなどに分割します。次に、各クラスに順番に呼び出すことができる to_str() メソッドがある出力を使用できます。

statements = [ ... ]

obj = open( "some.py", "w+" )

for s in statements:
    obj.write( s.to_str() )

obj.close()

このようにして、プロジェクトを簡単に拡張でき、より理解しやすく柔軟になります。そして、それはあなたが望んでいた単純な書き込み方法の使用にとどまります。

学習アルゴリズムによっては、さまざまなクラスからのこのブレークアウトが、コードの一種の疑似遺伝的アルゴリズムにつながる可能性があります。一連のステートメントとしてゲノムをエンコードできます。必要な場合は、各ステートメントにパラメーターを渡す方法を見つけるだけです。

于 2012-07-05T19:11:37.733 に答える
1

生成するコードで何をするかによって異なります。いくつかのオプションがあり、それぞれが前のオプションよりも高度です。

  • ファイルを作成してインポートする
  • 文字列を作成しexec
  • テキストとしてではなく、オンザフライで直接クラス (またはモジュール) を作成するコードを記述し、必要な関数をそれらに挿入します。
  • Python バイトコードを直接生成し、それを実行してください!

他のプログラマーによって使用および変更されるコードを作成している場合は、おそらく最初のアプローチが最適です。それ以外の場合は、ほとんどのユース ケースで 3 番目をお勧めします。最後は、マゾヒストと元アセンブリ言語プログラマーのみです。

既存の Python ソース コードを変更したい場合、特に使用しているソース ファイルについて何か知っている場合は、基本的な検索と置換を使用して単純な変更を行うだけで済む場合がありますが、より良い方法はastモジュールです。これにより、変更して直接 Python オブジェクトにコンパイルできる Python ソースの抽象表現が得られます。

于 2012-07-05T18:51:16.530 に答える