python import問題

16 回覆
0 Like 3 Dislike
2022-05-28 23:10:54
先利申: python bb班學員

小弟寫左2個py file + 1個txt file --> temp1.py & temp2.py & config.txt
- config.txt就係define csv file name, report name
- temp1就係根據config.txt入面csv file name去open相關csv file轉做一條n個element既list
如果run temp1.py就會出result_list = [1,...,n]
- temp2.py係用temp1條result_list plot圖:
import temp1
data = temp1.result_list
title_name = temp1.report_name
scat = px.scatter(temp1.result_list, title=title_name)

問題就係config.txt 改左第二個csv file & report name
temp2 run完data同title name冇update到 (即係keep返第一次run既list同report name)
只有熄左pycharm再開/手動run temp1.py先得
想問下可以點解決唔洗run temp1/重開就識update
感激不盡或者話我知用咩Keyword去google
2022-05-28 23:15:05
2022-05-28 23:15:16
2022-05-28 23:23:33
temp1果邊一定要寫做function先得?
2022-05-28 23:25:58
How to create a Minimal, Reproducible Example
https://stackoverflow.com/help/minimal-reproducible-example

利申so
2022-05-28 23:34:34
至少叫佢貼埋temp1 出嚟先啦
同埋唔好叫temp1, temp2
改個好啲嘅名
2022-05-28 23:35:00
巴打你咁都覆佢真好人
2022-05-28 23:40:22
sorry因為temp1只係open csv 同轉做list 我以為冇乜特別同上面位巴打唔同 我temp1唔係function大約係咁:
config_file = r'config.txt'
2022-05-28 23:46:02
禁錯
temp1:
config_file = r'config.txt'
c = open(os.getcwd()+'\\' + config_file, "r") 
report_name = get_name('report_name=', ',', 0)
csv_name = get_name('csv file=', settings, ',', 0)
c.close()


.
.
result_list = [1,....,n]

get_name係去拎config.txt入面既str
2022-05-29 00:18:27
你貼曬出嚟啦

你明唔明import variable 係做緊咩
如果好似你呢個咁
result_list = [1,....,n] 

咁你咪淨係import咗 [1,....,n]
所以最重要嘅嘢你咁啱就漏咗

如果你右手邊係function
例如
temp1.py
def read_config:
    // read some config
    return csv_file_name
def read_csv:
    // read some data
    return csv_data

csv_file_name = read_csv()

// read_config will be executed
result_list1 = read_csv(csv_file_name)
// read_config will NOT be executed
result_list2 = read_csv()

咁佢都只會為咗計 result_list 而淨係計minimal 有關嘅function
(我唔太肯定import variable behavior,除非import constant 好少咁做)

我覺得係你自己做錯咗咩都唔知
又或者係global local variable 有問題

一般計import functioni 易debug 好多
https://stackoverflow.com/questions/52641676/how-to-use-values-from-variables-imported-from-another-file-python
2022-05-29 10:52:37
點樣quote先有syntax highlight
吹水台自選台熱 門最 新手機台時事台政事台World體育台娛樂台動漫台Apps台遊戲台影視台講故台健康台感情台家庭台潮流台美容台上班台財經台房屋台飲食台旅遊台學術台校園台汽車台音樂台創意台硬件台電器台攝影台玩具台寵物台軟件台活動台電訊台直播台站務台黑 洞