1

私はPythonに比較的慣れていません。ですから、私の素朴さを許してください。文字列をファイルに書き込もうとすると、変数の後の文字列の部分が新しい行に置かれますが、そうすべきではありません。私はpython 2.6.5 btwを使用しています

arch = subprocess.Popen("info " + agent + " | grep '\[arch\]' | awk '{print $3}'", shell=True, stdout=subprocess.PIPE)
arch, err = arch.communicate()
strarch = str(arch)
with open ("agentInfo", "a") as info:
        info.write("Arch Bits: " + strarch + " bit")
        info.close()
os.system("cat agentInfo")

望ましい出力:

"Arch Bits: 64 bit"

実際の出力:

"Arch Bits: 64
bits"
4

1 に答える 1

3

str(arch)末尾に改行があるように見えますが、 str.striporを使用して削除できますstr.rstrip:

strarch = str(arch).strip()   #removes all types of white-space characters

また:

strarch = str(arch).rstrip('\n') #removes only trailing '\n'

また、ここで文字列の書式設定を使用することもできます。

strarch = str(arch).rstrip('\n')
info.write("{}: {} {}".format("Arch Bits", strarch, "bits"))

info.close()ステートメントは自動的にファイルを閉じる必要がないことに注意してください。with

于 2013-07-12T07:43:19.207 に答える