作者热门文章
- html - 出于某种原因,IE8 对我的 Sass 文件中继承的 html5 CSS 不友好?
- JMeter 在响应断言中使用 span 标签的问题
- html - 在 :hover and :active? 上具有不同效果的 CSS 动画
- html - 相对于居中的 html 内容固定的 CSS 重复背景?
给定这样的代码,我如何在运行选项中实际设置文件?
我正在使用Spyder,并已将-h -s -p -o
用作参数,但是我不确定如何为-o
选项指定命名文件。
class CommandLine:
def __init__(self):
opts, args = getopt.getopt(sys.argv[1:],'hspw:o:')
opts = dict(opts)
if '-o' in opts:
self.outfile = opts['-o']
else:
self.outfile = None
最佳答案
这是一个处理argpase的简单教程。
但是首先,如果您想在使用argparse模块时获得更多控制权,我建议您阅读official documentation。
另外,如果您想将参数传递给Spyder,我将推荐@Carlos Cordoba的答案,后者建议查看此answer。
我的教程脚本:
import argparse
class CommandLine:
def __init__(self):
parser = argparse.ArgumentParser(description = "Description for my parser")
parser.add_argument("-H", "--Help", help = "Example: Help argument", required = False, default = "")
parser.add_argument("-s", "--save", help = "Example: Save argument", required = False, default = "")
parser.add_argument("-p", "--print", help = "Example: Print argument", required = False, default = "")
parser.add_argument("-o", "--output", help = "Example: Output argument", required = False, default = "")
argument = parser.parse_args()
status = False
if argument.Help:
print("You have used '-H' or '--Help' with argument: {0}".format(argument.Help))
status = True
if argument.save:
print("You have used '-s' or '--save' with argument: {0}".format(argument.save))
status = True
if argument.print:
print("You have used '-p' or '--print' with argument: {0}".format(argument.print))
status = True
if argument.output:
print("You have used '-o' or '--output' with argument: {0}".format(argument.output))
status = True
if not status:
print("Maybe you want to use -H or -s or -p or -p as arguments ?")
if __name__ == '__main__':
app = CommandLine()
$ python3 my_script.py -H Help -s Save -p Print -o Output
You have used '-H' or '--Help' with argument: Help
You have used '-s' or '--save' with argument: Save
You have used '-p' or '--print' with argument: Print
You have used '-o' or '--output' with argument: Output
-h
或
--help
作为参数时,您将获得以下输出:
$ python3 my_script.py -h
usage: my_script.py [-h] [-H HELP] [-s SAVE] [-p PRINT] [-o OUTPUT]
Description for my parser
optional arguments:
-h, --help show this help message and exit
-H HELP, --Help HELP Example: Help argument
-s SAVE, --save SAVE Example: Save argument
-p PRINT, --print PRINT
Example: Print argument
-o OUTPUT, --output OUTPUT
Example: Output argument
关于python - 可选的命令行参数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/60457603/
我正在尝试用 Swift 编写这段 JavaScript 代码:k_combinations 到目前为止,我在 Swift 中有这个: import Foundation import Cocoa e
我是一名优秀的程序员,十分优秀!