今天寫了個python程序,代碼中有print,但是執行完后,輸出的結果就只有:
Process finished with exit code 0
並沒有將我打印的內容打印出來。
后來參考資料,總結有2點可能的原因:
1)File→settings→project→project interpreter設置的解釋器有問題(建議創建項目的時候選擇現有的配置好的解釋器,不要使用新的pycharm的虛擬解釋器,如圖。)
2)代碼格式問題——縮進不對(檢查一下代碼的縮進,實在覺得沒毛病,就把縮進都刪掉,重新縮進。)
我的是2)導致的。不過后面想再復現這個問題,復現不了。附上修改后的代碼吧。
附代碼:
'''
@Desc:1)requests模塊的方法;2)文件讀、寫
'''
import requests
class TestMain:
def test(self):
r = requests.get("http://www.baidu.com") # get請求百度首頁
print("訪問百度首頁的狀態碼、cookie、登錄狀態:", r.status_code, r.cookies, r.ok) # 打印響應碼
# 將get請求的響應內容寫入到項目文件夾下的text.txt(若文件不存在則新建文件)
with open("text.txt", 'w', encoding='utf-8') as f:
f.write(r.text)
# 讀取text.txt-讀取部分行
with open('F:\/cs_auto\/untitled1\/text.txt') as file_open: # 完整目錄等同於"text.txt"
print("以下只打印第一行:")
for i in range(1):
print(file_open.readline())
# 不需要file_open.close(),因為關鍵字with在我們不再需要使用文件的時候將其關閉。
# 讀取text.txt-讀取整個文件
with open('text.txt') as file_open:
print("以下打印文件的全部內容:")
print(file_open.read())
# 讀取text.txt-按行讀取文件內容
with open('text.txt') as file_open:
print("以下按行讀取並打印文件的全部內容:")
for content in file_open:
print(content.rstrip()) # 不調用rstrip()函數的話,會在每行后面多打印一個空行
if __name__ == '__main__':
print("this is main method")
TestMain.test('self')