![Bash를 통해 실행되는 Python 파일의 출력을 표시하고 저장합니다.](https://linux55.com/image/196376/Bash%EB%A5%BC%20%ED%86%B5%ED%95%B4%20%EC%8B%A4%ED%96%89%EB%90%98%EB%8A%94%20Python%20%ED%8C%8C%EC%9D%BC%EC%9D%98%20%EC%B6%9C%EB%A0%A5%EC%9D%84%20%ED%91%9C%EC%8B%9C%ED%95%98%EA%B3%A0%20%EC%A0%80%EC%9E%A5%ED%95%A9%EB%8B%88%EB%8B%A4..png)
저는 Linux와 프로그래밍 세계를 처음 접했기 때문에 제 질문은 매우 기초적일 수 있지만 어디에서도 답을 찾을 수 없습니다.
저는 쉘 파일을 사용하여 가상 클러스터에서 Python 파일을 실행하고 있습니다(회귀를 수행하므로 테이블을 얻을 것으로 예상됩니다). 작업이 제대로 시작되고 실행되지만 결과를 시각화하거나(메시지가 표시되면 인쇄) 출력이 포함된 파일을 만들 수 없습니다.
Python 파일의 결과를 보려면 어떻게 해야 합니까? Bash나 Python 코드에 넣을 수 있는 명령이 있나요?
python mycode.py > SomeFile.txt
SomeFile.txt라는 빈 txt 파일을 생성하는 bash에 다음 명령을 입력하는 등 작동하지 않는 몇 가지 솔루션을 시도했습니다 .
또한 tex 및 pickle 파일에서 결과를 얻기 위해 Python 코드에 다음 줄을 추가하려고 시도했지만 둘 중 하나도 작동하지 않았습니다.
print(f"Output file: {results.data.htmlFileName}")
results.writeLaTeX()
print(f'LaTeX file: {results.data.latexFileName}')
results.writePickle()
print(f'Pickle file: {results.data.pickleFileName}')
어떤 도움이라도 미리 감사드립니다 :)
클러스터에서 실행하려는 Python 코드에 대한 더 나은 아이디어를 얻기 위해 mycode.py의 스크립트 아래에 삽입했습니다. (작은 참고: 이것이 제가 실행하는 첫 번째 코드이므로 테스트로 5 Monte만 요청합니다. Carlo는 무승부지만 목표는 100000 무승부 이상을 요구하는 것입니다)
#Import packages
import pandas as pd
import biogeme.database as db
import biogeme.biogeme as bio
import biogeme.models as models
from biogeme.models import logit
from biogeme.expressions import Beta, DefineVariable, bioDraws, log, MonteCarlo
from datetime import datetime
#Prepare the data
step2_sup3_7ex = pd.read_table("step2_sup3_7ex.txt")
step2_sup3_7ex
database = db.Database("step2_sup3_7ex",step2_sup3_7ex)
# The following statement allows you to use the names of the variable
# as Python variable.
globals().update(database.variables)
#model specification
#parameters to be estimated: as a reference mode, we choose the car
#Alternative specific constant:
ASC_CAR = Beta ( "ASC_CAR" ,0 ,None ,None , 1 ) #1 as a last parameter so it will not be estimated since we decided to have the car as a reference alternative
ASC_PT = Beta ( "ASC_PT" ,0 ,None ,None , 0 )
ASC_BICYCLE = Beta ( "ASC_BICYCLE" ,0 ,None ,None , 0 )
#alternative specific attributes
#the used starting values are 0 because from exeperience with S2B3 using the starting values of prevous models gives results with low goodness of fit
B_COST = Beta("B_COST",0,None,None,0)
B_TIME_CAR = Beta("B_TIME_CAR",0,None,None,0)
B_TIME_PT = Beta("B_TIME_PT",0,None,None,0)
B_TIME_BICYCLE = Beta("B_TIME_BICYCLE",0,None,None,0)
B_POLL_mean = Beta("B_POLL_mean",0,None,None,0)
B_POLL_std = Beta("B_POLL_std",0.1,None,None,0)
B_PHYS_mean = Beta("B_PHYS_mean",0,None,None,0)
B_PHYS_std = Beta("B_PHYS_std",0.1,None,None,0)
#Individual effect of the % of people adopting a behavior
B_PRCT50 = Beta("B_PRCT50",0,None,None,1)
B_PRCT75 = Beta("B_PRCT75",0,None,None,0)
B_PRCT90 = Beta("B_PRCT90",0,None,None,0)
#we cross the level of risk of sickness due to air pollution with the % of people adopting the mobility behavior: pour chaque niveau on a un paramètre spécifique
B_POLL_PRCT50_mean = Beta("B_POLL_PRCT50_mean",0,None,None,1)
B_POLL_PRCT50_std = Beta("B_POLL_PRCT50_std",0.1,None,None,1)
B_POLL_PRCT75_mean = Beta("B_POLL_PRCT75_mean",0,None,None,0)
B_POLL_PRCT75_std = Beta("B_POLL_PRCT75_std",0.1,None,None,0)
B_POLL_PRCT90_mean = Beta("B_POLL_PRCT90_mean",0,None,None,0)
B_POLL_PRCT90_std = Beta("B_POLL_PRCT90_std",0.1,None,None,0)
#Risk variation (specific delta for each health attribute)
delta_POLL = Beta('delta_POLL',0,None,None,0) #delta is positive, varies from 0 to +infinity
delta_POLL75 = Beta('delta_POLL75',0,None,None,0)
delta_POLL90 = Beta('delta_POLL90',0,None,None,0)
delta_PHYS = Beta('delta_PHYS',0,None,None,0)
#parameters of the status quo
B_STAT_CAR = Beta("B_STAT_CAR",0,None,None,1)
B_STAT_PT = Beta("B_STAT_PT",0,None,None,0)
B_STAT_BICYCLE = Beta("B_STAT_BICYCLE",0,None,None,0)
#Socioeconomic parameters:
B_AGE = Beta('B_AGE',0,None,None,0)
B_AGE2 = Beta('B_AGE2',0,None,None,0)
B_GENDER = Beta('B_GENDER',0,None,None,0)
# Random parameters
B_PHYS_random = B_PHYS_mean + B_PHYS_std * bioDraws('B_PHYS_random','NORMAL')
B_POLL_random = B_POLL_mean + B_POLL_std * bioDraws('B_POLL_random','NORMAL')
B_POLL_PRCT50_random = B_POLL_PRCT50_mean + B_POLL_PRCT50_std * bioDraws('B_POLL_PRCT50_random', 'NORMAL')
B_POLL_PRCT75_random = B_POLL_PRCT75_mean + B_POLL_PRCT75_std * bioDraws('B_POLL_PRCT75_random', 'NORMAL')
B_POLL_PRCT90_random = B_POLL_PRCT90_mean + B_POLL_PRCT90_std * bioDraws('B_POLL_PRCT90_random', 'NORMAL')
#Utilities
U_CAR = ASC_CAR + B_TIME_CAR * temps1_C1Q + B_COST * cout1_C1Q
U_PT = (ASC_PT + B_TIME_PT * temps2_C1Q + B_COST * cout2_C1Q +
B_PHYS_random * (phys_act1_C1Q - phys_act2_C1Q)**delta_PHYS +
(B_POLL_random + B_POLL_PRCT75_random * prct75 + B_POLL_PRCT90_random * prct90 ) * (poll1_C1Q - poll2_C1Q)**(delta_POLL + delta_POLL75 * prct75 + delta_POLL90 * prct90) +
B_PRCT75 * prct75 + B_PRCT90 * prct90 +
B_STAT_PT * stat_TC + B_STAT_BICYCLE * stat_velo +
B_AGE * age_cont + B_AGE2 * age2_cont + B_GENDER * homme)
U_BICYCLE = (ASC_BICYCLE + B_TIME_BICYCLE * temps3_C1Q + B_COST * cout3_C1Q +
B_PHYS_random * (phys_act1_C1Q - phys_act3_C1Q)**delta_PHYS +
(B_POLL_random + B_POLL_PRCT75_random * prct75 + B_POLL_PRCT90_random * prct90 ) * (poll1_C1Q - poll3_C1Q)**(delta_POLL + delta_POLL75 * prct75 + delta_POLL90 * prct90) +
B_PRCT75 * prct75 + B_PRCT90 * prct90 +
B_STAT_PT * stat_TC + B_STAT_BICYCLE * stat_velo +
B_AGE * age_cont + B_AGE2 * age2_cont + B_GENDER * homme)
#associating the utility fcts with the numbering of the altrnatives
V = {5: U_CAR,
4: U_PT,
1: U_BICYCLE,
} #V is a python dictionnary
#associate the avaiability conditions with the alternatives
av = {5: 5,
4: 4,
1: 1,
} #dictionnary
# Choice model (Random coefficients/ mixed logit model)
prob = logit(V,av,choix_C1Q)
logprob = log(MonteCarlo(prob))
biogeme = bio.BIOGEME(database,logprob,numberOfDraws=5)
biogeme.modelName = "S2A3_MLdelta_5MC"
start_time = datetime.now()
# As the estimation may take a while and risk to be interrupted, we save the iterations,
# and restore them before the estimation.
fname = "__MLdelta5MC.iters"
biogeme.loadSavedIteration(filename=fname)
# Estimate the parameters.
results = biogeme.estimate(saveIterations=True, file_iterations=fname)
#read the results
print(f"Estimation time: {datetime.now() - start_time}")
# Get the results in a pandas table
pandasResults = results.getEstimatedParameters()
print(pandasResults)
print(f"Nbr of observations: {database.getNumberOfObservations()}")
print(f"LL(0) = {results.data.initLogLike:.3f}")
print(f"LL(beta) = {results.data.logLike:.3f}")
print(f"rho bar square = {results.data.rhoBarSquare:.3g}")
print(f"Output file: {results.data.htmlFileName}")
results.writeLaTeX()
print(f'LaTeX file: {results.data.latexFileName}')
results.writePickle()
print(f'Pickle file: {results.data.pickleFileName}')
답변1
유용하기에는 너무 늦었을지도 모르지만, 당신이 찾고 있는 것은 '-유' 논쟁.
$ man python
. . .
-u Force stdin, stdout and stderr to be totally unbuffered. On systems where it matters, also put stdin, stdout and stderr in binary mode. Note that there is internal buffering in xreadlines(), readlines() and file-object iterators ("for line in sys.stdin") which is not influenced by this option. To work around this, you will want to use "sys.stdin.readline()" inside a "while 1:" loop.
. . .
따라서 작업 파일에 다음을 넣어야 합니다:
python -u mycode.py > Somefile.text
또는 Python 파일 처리를 사용하여 데이터를 더 잘 관리하는 것이 좋습니다. 하지만 어떤 이유로든 할 수 없다면 위의 방법을 따르세요.