1

私はコーディングを学んでいますが、非常に新しいです。いくつかのスクリプトを作成しましたが、それらを 1 つのスクリプトに結合したいと考えています。私は本質的に「一見」しようとしています。ターミナルからコマンドを実行し、それをテキスト ファイルに入力してから、そのテキスト ファイルを開いて、その中の単語の操作を開始します。

私は多くの異なるバリエーションを試しました:

print "What file do you want to create? "
file_in = raw_input(">")
file_in = open(file_in, 'w')
new_file = os.system("look .")
file_in.write(new_file)

これにより、次の結果が得られます。

Traceback (most recent call last):
File "hash.py", line 13, in <module>
file_in.write(new_file)
TypeError: expected a character buffer object

すべての単語が画面に出力された後。

私もこれを試しました:

print "What file do you want to create? "
file_in = raw_input(">")
new_file = os.system("look . > "+file_in+".txt")

##This is attempting to open the file to make each word capital in the list, the list is     made at this point
capital_words=open(new_file, 'w')

しかし、これは次の結果になります。

capital_words = open(new_file, 'w')
TypeError: coercing to Unicode: need string or buffer, int found

capital_words を str に変換してみました。しかし、それは私にこれをさせません。スクリプトを使用してリストを作成できます。また、既存のリストを開いて、別のスクリプトを使用して各単語を大文字にすることもできますが (これはここで行うつもりです)、それらを組み合わせるとこの問題が発生します。

どんな助けでも大歓迎です。

(これには実用的なアプリケーションがないことはわかっています。プログラミングの基礎を学ぼうとしているだけです)

4

1 に答える 1

1

このos.system呼び出しは、呼び出したプログラムの出力を返しません。終了コードを返します。subprocessプログラムの出力をキャプチャするには、モジュールを使用する必要があり、 を呼び出しPopenて出力をキャプチャしますsubprocess.PIPE

方法は次のとおりです。

import subprocess
# Create a Popen object that captures the output.
p=subprocess.Popen(['look','data'],stdout=subprocess.PIPE)
# Call 'look data' and wait for it to finish.
p.wait()
# Now read the output.
print p.stdout.read()

これにより、次が生成されます。

data
database
database's
databases

出力をファイルにダンプするには、代わりに次のprint p.stdout.read()ようにする必要があります。

import subprocess
with open('foobar.txt', 'w') as f:
  p=subprocess.Popen(['look','data'], stdout=f)
  p.wait()
于 2013-09-28T09:19:42.340 に答える