简体   繁体   English

在Python中从命令行输入变量

[英]Input variable from command line in Python

What I want to do is very simple but I can't figure out a good and not too complex solution for this. 我想做的事情很简单,但是我无法为此找到一个好的且不太复杂的解决方案。 Basically I want to define some global variables that will be used for example as a folder name 基本上,我想定义一些全局变量,例如,将其用作文件夹名称

global folder = "C:\\TEMP\\" + foldername

And what I want is to set the foldername value as input when running the script, something like: 我想要的是在运行脚本时将foldername值设置为输入,例如:

python myscript.py --folder somebeautifulfoldername

so when running my script, the folder will become C:\\TEMP\\somebeautifulfoldername 因此,在运行脚本时,该文件夹将变为C:\\ TEMP \\ somebeautifulfoldername

You can use the built-in argparse module for this combined with getting the command line arguments from sys.argv : 您可以为此使用内置的argparse模块,并结合从sys.argv获取命令行参数:

import argparse
import sys

if __name__ == '__main__':
    parser = argparse.ArgumentParser(description = 'My script')
    parser.add_argument('--folder', help = "Subfolder of C:\TEMP\ to manipulate")
    args = parser.parse_args(sys.argv[1:])
    folder = "C:\\TEMP\\"+args.folder
    print folder

Here I added just a very simple argument with some basic help string, but you can do quite a lot with this like giving a default value, allowing a list of files instead of a single file, specify the type, ... . 在这里,我只添加了一个非常简单的参数以及一些基本的帮助字符串,但是您可以做很多事情,例如提供默认值,允许使用文件列表而不是单个文件,指定类型...。 See the manual for more details and examples. 有关更多详细信息和示例,请参见手册。

Usage: 用法:

>python myscript.py --folder somebeautifulfoldername
C:\TEMP\somebeautifulfoldername

>python myscript.py --help
usage: tmp.py [-h] [--folder FOLDER]

My script

optional arguments:
  -h, --help       show this help message and exit
  --folder FOLDER  Subfolder of C:\TEMP\ to manipulate

You can pass arguments to Python script like following: 您可以将参数传递给Python脚本,如下所示:

python test.py arg1 arg2 arg3

And this is what you get 这就是你得到的

Argument List: ['test.py', 'arg1', 'arg2', 'arg3']

In your case: 在您的情况下:

python myscript.py somebeautifulfoldername

folder = "C:\\\\TEMP\\\\" + sys.argv[1]

import sys

folder = "none"
if("--folder" in  sys.argv):
    folder = sys.argv[sys.argv.index("--folder") + 1]        
print folder

If you run it the way you want: 如果以所需方式运行它:

python myscript.py --folder "HELLOFOLDER"

It will give: HELLOFOLDER 它将给出:HELLOFOLDER

There are a number of options to parse command line arguments into a Python script. 有许多选项可将命令行参数解析为Python脚本。 There's the standard library's optparse and argparse for instance. 例如,有标准库的optparseargparse

A really nice 3rd party tool is docopt , which allows you to write the logic described above very easily by describing the script usage directly as documentation of your script like this: 一个非常不错的第三方工具docopt ,通过将脚本用法直接描述为脚本文档,您可以非常轻松地编写上述逻辑:

"""My script

Usage:
  myscript.py --folder=<folder>

Options:
  -h --help             Show this screen.
  --version             Show version.
  --folder=<folder>     Choose folder.
"""

from docopt import docopt

if __name__ == '__main__':
    arguments = docopt(__doc__, version='myscript 1.0')
    folder = "C:\\TEMP\\" + arguments["--folder"]
    print(folder)

That said, you may also want to look into tempfile for generating temporary files to make the script more cross-platform. 也就是说,您可能还希望研究用于生成临时文件的tempfile ,以使脚本更具跨平台性。 Hard-coding Windows-specific paths is rarely a good idea. 硬编码Windows专用路径很少是个好主意。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM