views:

259

answers:

9

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

For example:

C:/Program/App.exe -safemode
+2  A: 

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

Austin Salonen
FWIW, I know this isn't a great answer but it does show off how simple it is to look this stuff up on your own.
Austin Salonen
+9  A: 

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.

SilentGhost
+3  A: 

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.

Enrico Carlesso
A: 

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".

jsn
A: 

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

Philip Fourie
+2  A: 

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
gotgenes
could you give an simpler example? =p
Shady
+6  A: 

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,
    )
Joe Koberg
but where inside the add_option I put my source to that option?
Shady
`options, arguments = parser.parse_args()` will put flags for all the options into the variable `options`.... then it's up to you to write an `if` or whatever that checks those flags and runs the code you wish.(You can *technically* provide a function to the option parser, but I think it's easier to understand if you just use it to parse and set the flags)
Joe Koberg
My intention here is make 3 command lines, witch each one will take a specific resolution... for example, app.exe -1024 will run the program in 1024x768... where exactly I put the resolution code in there... I didnt get yet =/
Shady
I have added a parameter for `width`. But I do suggest you read the documentation at http://docs.python.org/library/optparse.html
Joe Koberg
could you give me your msn Joe?
Shady
If you're asking for my instant messenger contact - that's a very firm NO.
Joe Koberg
ok, hunf =(Let me try explain here:I want 6 modes of vids, 1024x768, etc... and I want that the program resizes the windows using the parameters, for example app.exe -mode1, and if no parameter is typed, the program do nothing...Im not expert at python, Im just a beginner, and I've already have the resize command, only need the parameter options... and Im not having too much success here =/
Shady
A: 

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

Charles Merriam
A: 

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.

N 1.1