如何在python中使用终端命令写入文件?

时间:2013-09-28 08:08:06

标签: python-2.7

我正在学习编码,我很新。我编写了一些脚本,并希望将它们组合成一个脚本。我基本上试图采取“看”。来自终端的命令,将其输入到文本文件中,然后打开该文本文件以开始操作其中的单词。

我尝试了很多不同的变体:

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。但它根本不会让我这样做。我可以使用脚本创建列表,我可以使用单独的脚本打开现有列表并将每个单词(这是我打算在这里做的)大写,但是当我将它们组合时我遇到了这个问题。

感谢任何帮助。

(我知道这没有任何实际应用,我只是想学习编程的基础知识)

1 个答案:

答案 0 :(得分: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()