In Python, how to supply the command line arguments in interactive mode - python

I am new to Python. I want to run a software in interactive mode. In the manual it says the usage
python experiment.py --config config.yaml --out result/
The question is, how can I supply the command line arguments to experiment.py in interactive mode?

The commandline arguments that e.g. optparse and argparse uses are taken by default from sys.argv element 1 and up. You can always do:
import sys
sys.argv[1:] = ['--config', 'config.yaml', '--out', 'result/']
Although e.g. in argparse you can provide the arguments explicitly to .parse_args() as well and then that method will not inspect sys.argv

If I understood you correctly you need something like this:
while True:
query = raw_input("> ")
if query == "exit":
break
# do something useful

Related

Forward a shell command using python

So to be more precise, what I am trying to do is :
read a full shell command as argument of my python script like : python myPythonScript.py ls -Fl
Call that command within my python script when I'd like to (Make some loops on some folders and apply the command etc ...)
I tried this :
import subprocess
from optparse import OptionParser
from subprocess import call
def execCommand(cmd):
call(cmd)
if __name__ == '__main__':
parser = OptionParser()
(options,args) = parser.parse_args()
print args
execCommand(args)
The result is that now I can do python myPythonScript.py ls , but I don't know how to add options. I know I can use parser.add_option , but don't know how to make it work for all options as I don't want to make only specific options available, but all possible options depending on the command I am running.
Can I use something like parser.add_option('-*') ? How can I parse the options then and call the command with its options ?
EDIT
I need my program to parse all type of commands passed as argument : python myScript.py ls -Fl , python myScript.py git pull, python myScript rm -rf * etc ...
OptionParser is useful when your own program wants to process the arguments: it helps you turn string arguments into booleans or integers or list items or whatever. In your case, you just want to pass the arguments on to the program you're invoking, so don't bother with OptionParser. Just pass the arguments as given in sys.argv.
subprocess.call(sys.argv[1:])
Depending on how much your program depends on command line arguments, you can go with simple route.
Simple way of reading command line arguments
Use sys to obtain all the arguments to python command line.
import sys
print sys.argv[1:]
Then you can use subprocess to execute it.
from subprocess import call
# e.g. call(["ls", "-l"])
call(sys.argv[1:])
This sample below works fine for me.
import sys
from subprocess import call
print(sys.argv[1:])
call(sys.argv[1:])

Pass arguments from cmd to python script [duplicate]

This question already has answers here:
How to read/process command line arguments?
(22 answers)
Closed 2 years ago.
I write my scripts in python and run them with cmd by typing in:
C:\> python script.py
Some of my scripts contain separate algorithms and methods which are called based on a flag.
Now I would like to pass the flag through cmd directly rather than having to go into the script and change the flag prior to run, I want something similar to:
C:\> python script.py -algorithm=2
I have read that people use sys.argv for almost similar purposes however reading the manuals and forums I couldn't understand how it works.
There are a few modules specialized in parsing command line arguments: getopt, optparse and argparse. optparse is deprecated, and getopt is less powerful than argparse, so I advise you to use the latter, it'll be more helpful in the long run.
Here's a short example:
import argparse
# Define the parser
parser = argparse.ArgumentParser(description='Short sample app')
# Declare an argument (`--algo`), saying that the
# corresponding value should be stored in the `algo`
# field, and using a default value if the argument
# isn't given
parser.add_argument('--algo', action="store", dest='algo', default=0)
# Now, parse the command line arguments and store the
# values in the `args` variable
args = parser.parse_args()
# Individual arguments can be accessed as attributes...
print args.algo
That should get you started. At worst, there's plenty of documentation available on line (say, this one for example)...
It might not answer your question, but some people might find it usefull (I was looking for this here):
How to send 2 args (arg1 + arg2) from cmd to python 3:
----- Send the args in test.cmd:
python "C:\Users\test.pyw" "arg1" "arg2"
----- Retrieve the args in test.py:
print ("This is the name of the script= ", sys.argv[0])
print("Number of arguments= ", len(sys.argv))
print("all args= ", str(sys.argv))
print("arg1= ", sys.argv[1])
print("arg2= ", sys.argv[2])
Try using the getopt module. It can handle both short and long command line options and is implemented in a similar way in other languages (C, shell scripting, etc):
import sys, getopt
def main(argv):
# default algorithm:
algorithm = 1
# parse command line options:
try:
opts, args = getopt.getopt(argv,"a:",["algorithm="])
except getopt.GetoptError:
<print usage>
sys.exit(2)
for opt, arg in opts:
if opt in ("-a", "--algorithm"):
# use alternative algorithm:
algorithm = arg
print "Using algorithm: ", algorithm
# Positional command line arguments (i.e. non optional ones) are
# still available via 'args':
print "Positional args: ", args
if __name__ == "__main__":
main(sys.argv[1:])
You can then pass specify a different algorithm by using the -a or --algorithm= options:
python <scriptname> -a2 # use algorithm 2
python <scriptname> --algorithm=2 # ditto
See: getopt documentation

When running a python script in IDLE, is there a way to pass in command line arguments (args)?

I'm testing some python code that parses command line input. Is there a way to pass this input in through IDLE? Currently I'm saving in the IDLE editor and running from a command prompt.
I'm running Windows.
It doesn't seem like IDLE provides a way to do this through the GUI, but you could do something like:
idle.py -r scriptname.py arg1 arg2 arg3
You can also set sys.argv manually, like:
try:
__file__
except:
sys.argv = [sys.argv[0], 'argument1', 'argument2', 'argument2']
(Credit http://wayneandlayne.com/2009/04/14/using-command-line-arguments-in-python-in-idle/)
In a pinch, Seth's #2 worked....
2) You can add a test line in front of your main function call which
supplies an array of arguments (or create a unit test which does the
same thing), or set sys.argv directly.
For example...
sys.argv = ["wordcount.py", "--count", "small.txt"]
Here are a couple of ways that I can think of:
1) You can call your "main" function directly on the IDLE console with arguments if you want.
2) You can add a test line in front of your main function call which supplies an array of arguments (or create a unit test which does the same thing), or set sys.argv directly.
3) You can run python in interactive mode on the console and pass in arguments:
C:\> python.exe -i some.py arg1 arg2
Command-line arguments have been added to IDLE in Python 3.7.4+. To auto-detect (any and older) versions of IDLE, and prompt for command-line argument values, you may paste (something like) this into the beginning of your code:
#! /usr/bin/env python3
import sys
def ok(x=None):
sys.argv.extend(e.get().split())
root.destroy()
if 'idlelib.rpc' in sys.modules:
import tkinter as tk
root = tk.Tk()
tk.Label(root, text="Command-line Arguments:").pack()
e = tk.Entry(root)
e.pack(padx=5)
tk.Button(root, text="OK", command=ok,
default=tk.ACTIVE).pack(pady=5)
root.bind("<Return>", ok)
root.bind("<Escape>", lambda x: root.destroy())
e.focus()
root.wait_window()
You would follow that with your regular code. ie. print(sys.argv)
Note that with IDLE in Python 3.7.4+, when using the Run... Customized command, it is NOT necessary to import sys to access argv.
If used in python 2.6/2.7 then be sure to capitalize: import Tkinter as tk
For this example I've tried to strike a happy balance between features & brevity. Feel free to add or take away features, as needed!
Based on the post by danben, here is my solution that works in IDLE:
try:
sys.argv = ['fibo3_5.py', '30']
fibonacci(int(sys.argv[1]))
except:
print(str('Then try some other way.'))
Auto-detect IDLE and Prompt for Command-line Arguments
#! /usr/bin/env python3
import sys
# Prompt user for (optional) command line arguments, when run from IDLE:
if 'idlelib' in sys.modules: sys.argv.extend(input("Args: ").split())
Change "input" to "raw_input" for Python2.
This code works great for me, I can use "F5" in IDLE and then call again from the interactive prompt:
def mainf(*m_args):
# Overrides argv when testing (interactive or below)
if m_args:
sys.argv = ["testing mainf"] + list(m_args)
...
if __name__ == "__main__":
if False: # not testing?
sys.exit(mainf())
else:
# Test/sample invocations (can test multiple in one run)
mainf("--foo=bar1", "--option2=val2")
mainf("--foo=bar2")
Visual Studio 2015 has an addon for Python. You can supply arguments with that. VS 2015 is now free.
import sys
sys.argv = [sys.argv[0], '-arg1', 'val1', '-arg2', 'val2']
//If you're passing command line for 'help' or 'verbose' you can say as:
sys.argv = [sys.argv[0], '-h']
IDLE now has a GUI way to add arguments to sys.argv! Under the 'Run' menu header select 'Run... Customized' or just Shift+F5...A dialog will appear and that's it!
Answer from veganaiZe produces a KeyError outside IDLE with python 3.6.3. This can be solved by replacing if sys.modules['idlelib']: by if 'idlelib' in sys.modules: as below.
import argparse
# Check if we are using IDLE
if 'idlelib' in sys.modules:
# IDLE is present ==> we are in test mode
print("""====== TEST MODE =======""")
args = parser.parse_args([list of args])
else:
# It's command line, this is production mode.
args = parser.parse_args()
There seems like as many ways to do this as users. Me being a noob, I just tested for arguments (how many). When the idle starts from windows explorer, it has just one argument (... that is len(sys.argv) returns 1) unless you started the IDLE with parameters. IDLE is just a bat file on Windows ... that points to idle.py; on linux, I don't use idle.
What I tend to do is on the startup ...
if len(sys.argv) == 1
sys.argv = [sys.argv[0], arg1, arg2, arg3....] <---- default arguments here
I realize that is using a sledge hammer but if you are just bringing up the IDLE by clicking it in the default install, it will work. Most of what I do is call the python from another language, so the only time it makes any difference is when I'm testing.
It is easy for a noob like me to understand.

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

How can I process command line arguments in Python? [duplicate]

This question already has answers here:
How to read/process command line arguments?
(22 answers)
Closed last month.
What would be an easy expression to process command line arguments if I'm expecting anything like 001 or 999 (let's limit expectations to 001...999 range for this time), and few other arguments passed, and would like to ignore any unexpected?
I understand if for example I need to find out if "debug" was passed among parameters it'll be something like that:
if 'debug' in argv[1:]:
print 'Will be running in debug mode.'
How to find out if 009 or 575 was passed?
All those are expected calls:
python script.py
python script.py 011
python script.py 256 debug
python script.py 391 xls
python script.py 999 debug pdf
At this point I don't care about calls like that:
python script.py 001 002 245 568
python script.py some unexpected argument
python script.py 0001
python script.py 02
...first one - because of more than one "numeric" argument; second - because of... well, unexpected arguments; third and fourth - because of non-3-digits arguments.
As others answered, optparse is the best option, but if you just want quick code try something like this:
import sys, re
first_re = re.compile(r'^\d{3}$')
if len(sys.argv) > 1:
if first_re.match(sys.argv[1]):
print "Primary argument is : ", sys.argv[1]
else:
raise ValueError("First argument should be ...")
args = sys.argv[2:]
else:
args = ()
# ... anywhere in code ...
if 'debug' in args:
print 'debug flag'
if 'xls' in args:
print 'xls flag'
EDIT: Here's an optparse example because so many people are answering optparse without really explaining why, or explaining what you have to change to make it work.
The primary reason to use optparse is it gives you more flexibility for expansion later, and gives you more flexibility on the command line. In other words, your options can appear in any order and usage messages are generated automatically. However to make it work with optparse you need to change your specifications to put '-' or '--' in front of the optional arguments and you need to allow all the arguments to be in any order.
So here's an example using optparse:
import sys, re, optparse
first_re = re.compile(r'^\d{3}$')
parser = optparse.OptionParser()
parser.set_defaults(debug=False,xls=False)
parser.add_option('--debug', action='store_true', dest='debug')
parser.add_option('--xls', action='store_true', dest='xls')
(options, args) = parser.parse_args()
if len(args) == 1:
if first_re.match(args[0]):
print "Primary argument is : ", args[0]
else:
raise ValueError("First argument should be ...")
elif len(args) > 1:
raise ValueError("Too many command line arguments")
if options.debug:
print 'debug flag'
if options.xls:
print 'xls flag'
The differences here with optparse and your spec is that now you can have command lines like:
python script.py --debug --xls 001
and you can easily add new options by calling parser.add_option()
Have a look at the optparse module. Dealing with sys.argv yourself is fine for really simple stuff, but it gets out of hand quickly.
Note that you may find optparse easier to use if you can change your argument format a little; e.g. replace debug with --debug and xls with --xls or --output=xls.
optparse is your best friend for parsing the command line. Also look into argparse; it's not in the standard library, though.
If you want to implement actual command line switches, give getopt a look. It's incredibly simple to use, too.
Van Gale is largely correct in using the regular expression against the argument. However, it is NOT absolutely necessary to make everything an option when using optparse, which splits sys.argv into options and arguments, based on whether a "-" or "--" is in front or not. Some example code to go through just the arguments:
import sys
import optparse
claParser = optparse.OptionParser()
claParser.add_option(
(opts, args) = claParser.parse_args()
if (len(args) >= 1):
print "Arguments:"
for arg in args:
print " " + arg
else:
print "No arguments"
sys.exit(0)
Yes, the args array is parsed much the same way as sys.argv would be, but the ability to easily add options if needed has been added. For more about optparse, check out the relevant Python doc.

Categories