[英]How to export python output from terminal (function code)?
我有一段代碼試圖導出輸出。 我試過了,但唯一的問題是 ~str~ 必須在哪里以及必須是什么。
with open("piStorage.txt", "w") as fp:
fp.write(~str~)
這是我找到 ~str~ 的代碼
import csv
import time
start_time = time.time()
def calcPi(limit):
q, r, t, k, n, l = 1, 0, 1, 1, 3, 3
decimal = limit
counter = 0
while counter != decimal + 1:
if 4 * q + r - t < n * t:
yield n
if counter == 0:
yield '.'
if decimal == counter:
print('')
break
counter += 1
nr = 10 * (r - n * t)
n = ((10 * (3 * q + r)) // t) - 10 * n
q *= 10
r = nr
else:
nr = (2 * q + r) * l
nn = (q * (7 * k) + 2 + (r * l)) // (t * l)
q *= k
t *= l
l += 2
k += 1
n = nn
r = nr
def main():
pi_digits = calcPi(int(input(
"Enter the number of decimals to calculate to: ")))
i = 0
for d in pi_digits:
print(d, end='')
i += 1
if i == 200:
print("")
i = 0
if __name__ == '__main__':
main()
print("--- %s seconds ---" % (time.time() - start_time))
with open("piStorage.txt", "w") as fp:
fp.write(main)
我嘗試使用它,但它不起作用。 它出現了:“
追溯(最近一次通話):
文件“c:\Users\William\Desktop\pi.py”,第 48 行,在 <module> 中
fp.write(主要)
類型錯誤:write() 參數必須是 str,而不是函數
“
with open("piStorage.txt", "w") as fp:
fp.write(main)
您可以使用contextlib.redirect_stdout
。
def main():
pi_digits = calcPi(int(input(
"Enter the number of decimals to calculate to: ")))
i = 0
from contextlib import redirect_stdout
with open("piStorage.txt", "w") as fp:
with redirect_stdout(fp):
for d in pi_digits:
print(d, end='')
i += 1
if i == 200:
print("")
i = 0
fp.write(main)
由於您使用的是不帶括號()
的函數名稱,因此 this 指的是函數對象本身。
我想你是想用括號調用函數:
fp.write(main())
這將調用main()
並將其返回值寫入文件。
但是在這種情況下仍然行不通,因為您編寫main()
的方式實際上並沒有返回任何內容。
您需要更改main()
以便它直接寫入文件,而不是調用print()
。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.