Python 将脚本中的任何错误打印到文件-stderr
我有一个python程序,它接受三个命令行参数-f(file1)-n(file2)-o(file3) 该计划的结构如下:Python 将脚本中的任何错误打印到文件-stderr,python,console,stderr,Python,Console,Stderr,我有一个python程序,它接受三个命令行参数-f(file1)-n(file2)-o(file3) 该计划的结构如下: ffile='' nfile='' ofile='' try: myopts, args = getopt.getopt(sys.argv[1:],"f:n:o:h:") for x,y in myopts: if x == '-f': ffile=y elif x == '-n': nfile
ffile=''
nfile=''
ofile=''
try:
myopts, args = getopt.getopt(sys.argv[1:],"f:n:o:h:")
for x,y in myopts:
if x == '-f':
ffile=y
elif x == '-n':
nfile=y
elif x == '-o':
ofile=y
<do something here with the files>
except:
sys.stderr("err.txt",w)
sys.exit(2)
ffile=''
nfile=''
ofile=''
尝试:
myopts,args=getopt.getopt(sys.argv[1:],“f:n:o:h:)
对于myOpt中的x,y:
如果x='-f':
ffile=y
elif x=='-n':
n文件=y
elif x=='-o':
ofile=y
除:
sys.stderr(“err.txt”,w)
系统出口(2)
我想做的是:
但是,err.txt文件为空。我不知道发生了什么事。我见过许多问题,其中stderr被写入文件,但它似乎并没有回答我的问题 如果您愿意改变您的方法,我建议您不要尝试重新发明轮子,并查看一些现有的python库来完成此功能 有一个名为的库可以很好地解析命令行参数并返回适当的错误消息,也许您会发现它很有用
import argparse
p = argparse.ArgumentParser(description='My Program', formatter_class=argparse.ArgumentDefaultsHelpFormatter)
p.add_argument("-f", type=str, help="-f file", required=True)
p.add_argument("-n", type=str, help="-n file", required=True)
p.add_argument("-o", type=str, help="-o file", default=None)
args = p.parse_args() # will throw error if required -f and -n args not passed
在错误日志方面,您可以尝试使用python库。此库可以配置为将信息记录到标准输出、文本文件等,并且可能足够灵活以满足您的要求。非常感谢!!这太棒了