使我的 for 循环可执行
我已经在 Python 中创建了这个工作 for 循环:
a = 'word'
for i in range(len(a)):
print a[i:] + a[:i], (a[i:] + a[:i])[::-1]
我需要使其可以从命令行执行,并且还能够接受新参数。
我对如何做到这一点有点模糊。我知道您需要
if __name__ == '__main__':
以某种方式使用...而且我需要使用 sys.argv
如果有人可以解释如何执行此操作,以及从命令行使任何脚本可执行的格式,我将非常感激。
I've created this working for loop in Python:
a = 'word'
for i in range(len(a)):
print a[i:] + a[:i], (a[i:] + a[:i])[::-1]
and I need to make it executable from the command line and also have it be able to take in new arguments.
I'm a little hazy on how to do this. I know that you need to use
if __name__ == '__main__':
somehow...And that I need to use sys.argv
If anyone could explain how to do this, and the format for making any script executable from the command line, I would really appreciate it.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
您可以简单地编写
然后运行:
这
不是必需的,但您也可以将整个代码放在该下面。其目的是指定仅当您运行“python yourcode.py”之类的程序时才执行的代码,并防止在另一个 .py 文件中写入“import yourcode”时执行该 if 语句下的代码。
You can just simply write
And then run:
The
is not required, but you can also put your whole code under that. It's purpose is to specify code which gets executed only if you run your program like "python yourcode.py" and to prevent the code under that if statement from getting executed if you write "import yourcode" in another .py file.
根据您希望 Python 脚本的灵活性,我会像这样构建脚本:
有各种模块可以解析命令行参数。看看
argparse
(更简单)和optparse
。如果您只需要一种简单的方法来访问命令行参数,您可以使用
sys.argv
。通过这种分离,您还可以将函数导入到其他代码中。
示例:
运行它
并使用另请参阅:
if __name__=="__main__":
做什么?Depending on how flexible you want to have your Python script, I would structure the script like so:
There are various modules to parse command line arguments. Have a look at
argparse
(easier) andoptparse
.If you just need a simple way to access the command line arguments, you can go with
sys.argv
.With this separation you are also able to import your function into other code.
Example:
and run it with
See also:
if __name__=="__main__":
do?然后,您只需更改到包含该文件的目录,并像这样调用它:
在命令行上。
Then you simply change to the directory with the file, and call it like:
On the command line.