开发者

How do I make a command line program that takes arguments?

How can I make a command line, so I can execute my program on Windows with some parameters...开发者_StackOverflow

For example:

C:/Program/App.exe -safemode


have a look at the getopt and optparse modules from the standard lib, many good things could be also said about more advanced argparse module.

Generally you just need to access sys.argv.


I sense that you also want to generate an 'executable' that you can run standalone.... For that you use py2exe

Here is a complete example.py:

import optparse

parser = optparse.OptionParser()

parser.add_option("-s", "--safemode",
                  default = False,
                  action = "store_true",
                  help = "Should program run in safe mode?")

parser.add_option("-w", "--width",
                  type = "int",
                  default = 1024,
                  help = "Desired screen width in pixels")

options, arguments = parser.parse_args()

if options.safemode:
    print "Proceeding safely"
else:
    print "Proceeding dangerously"

if options.width == 1024:
    print "running in 1024-pixel mode"
elif options.width == 1920:
    print "running in 1920-pixel mode"

And here is a complete setup.py that will turn the above example.py into example.exe (in the dist subdirectory):

from distutils.core import setup
import py2exe
import sys

sys.argv.append('py2exe')

setup(
    options = {'py2exe': dict(bundle_files=1, optimize=2)},
    console = ["example.py"],
    zipfile = None,
    )


Are you speaking about parameter passed to a python script?

'couse you can access them by

import sys
print sys.argv

Or can use a more sophisticated getopt module.


Not a python guy (yet anyway) but my Google-fu found this assuming you meant "handling command line arguments":
http://www.faqs.org/docs/diveintopython/kgp_commandline.html


Use optparse.OptionParser.

from optparse import OptionParser
import sys

def make_cli_parser():
    """Makes the parser for the command line interface."""
    usage = "python %prog [OPTIONS]"
    cli_parser = OptionParser(usage)
    cli_parser.add_option('-s', '--safemode', action='store_true',
            help="Run in safe mode")
    return cli_parser

def main(argv):
    cli_parser = make_cli_parser()
    opts, args = cli_parser.parse_args(argv)
    if opts.safemode:
        print "Running in safe mode."
    else:
        print "Running with the devil."


if __name__ == '__main__':
    main(sys.argv[1:])

In use:

$ python opt.py
Running with the devil.
$ python opt.py -s
Running in safe mode.
$ python opt.py -h

Usage: python opt.py [OPTIONS]
Options:
  -h, --help      show this help message and exit
  -s, --safemode  Run in safe mode


Or are you just asking how to open a command line?

go to the start menu, click "run" (or just type, in Windows 7), type "cmd"

This will open up a command shell. Given that your question is tagged python, I'm not sure it's going to be compiled into an exe, you might have to type "python (your source here).py -safemode".


The other comments addressed how to handle parameters. If you want to make your python program an exe you might want to look at py2exe.

This is not required but you mentioned App.exe and not App.py


You are asking a question that has several levels of answers.

First, command line is passed into the array sys.argv. argv is a historic name from C and Unix languages. So:

~/p$ cat > args.py
import sys
print "You have ", len(sys.argv), "arguments."
for i in range(len(sys.argv)):
print "argv[", i, "] = ", sys.argv[i]

~/p$ python args.py 34 2 2 2
You have  5 arguments.
argv[ 0 ] =  args.py
argv[ 1 ] =  34
argv[ 2 ] =  2
argv[ 3 ] =  2
argv[ 4 ] =  2

This works both in MS Windows and Unix.

Second, you might be asking "How do I get nice arguments? Have it handle /help in MS Windows or --help in Linux?"

Well, there are three choices which try to do what you want. Two, optparse and getopt are already in the standard library, while argparse is on its way. All three of these are libraries that start with the sys.argv array of strings, a description of you command line arguments, and return some sort of data structure or class from which you can get the options you mean.

  • getopt does the minimal job. It does not provide "/help" or "--help".
  • optparse does a more detailed job. It provides "/help" and both short and long versions of options, e.g., "-v" and "--verbose".
  • argparse handles the kitchen sink, including "/help", short and long commands, and also subcommand structures, as you see in source control "git add ....", and positional arguments.

As you move to the richer parsing, you need to give the parser more details about what you want the command line arguments to be. For example, you need to pass a long written description of the argument if you want the --help argument to print it.

Third, you might be asking for a tool that just deals with the options from the command line, environment variables and configuration files. Python currently has separate tools for each of these. Perhaps I'll write a unified one, You will need: - Command line arguments parsed by argparse, or getopt, etc. - Environment variables, from os.environ[] - Configuration files from ConfigFile or plistlib, etc. and build your own answer to "what are the settings"?

Hope this fully answers your questions


One of the many ways:

import sys
print sys.argv

>>>python arg.py arg1 arg2
['arg.py', 'arg1', 'arg2']



sys.argv is a list containing all the arguments (also the name of script/program) as string.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜