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:])
Related
I would like to run a command in Python Shell to execute a file with an argument.
For example: execfile("abc.py") but how to add 2 arguments?
Actually, wouldn't we want to do this?
import sys
sys.argv = ['abc.py','arg1', 'arg2']
execfile('abc.py')
execfile runs a Python file, but by loading it, not as a script. You can only pass in variable bindings, not arguments.
If you want to run a program from within Python, use subprocess.call. E.g.
import subprocess
subprocess.call(['./abc.py', arg1, arg2])
try this:
import sys
sys.argv = ['arg1', 'arg2']
execfile('abc.py')
Note that when abc.py finishes, control will be returned to the calling program. Note too that abc.py can call quit() if indeed finished.
import sys
import subprocess
subprocess.call([sys.executable, 'abc.py', 'argument1', 'argument2'])
For more interesting scenarios, you could also look at the runpy module. Since python 2.7, it has the run_path function. E.g:
import runpy
import sys
# argv[0] will be replaced by runpy
# You could also skip this if you get sys.argv populated
# via other means
sys.argv = ['', 'arg1' 'arg2']
runpy.run_path('./abc.py', run_name='__main__')
You're confusing loading a module into the current interpreter process and calling a Python script externally.
The former can be done by importing the file you're interested in. execfile is similar to importing but it simply evaluates the file rather than creates a module out of it. Similar to "sourcing" in a shell script.
The latter can be done using the subprocess module. You spawn off another instance of the interpreter and pass whatever parameters you want to that. This is similar to shelling out in a shell script using backticks.
You can't pass command line arguments with execfile(). Look at subprocess instead.
If you set PYTHONINSPECT in the python file you want to execute
[repl.py]
import os
import sys
from time import time
os.environ['PYTHONINSPECT'] = 'True'
t=time()
argv=sys.argv[1:len(sys.argv)]
there is no need to use execfile, and you can directly run the file with arguments as usual in the shell:
python repl.py one two 3
>>> t
1513989378.880822
>>> argv
['one', 'two', '3']
If you want to run the scripts in parallel and give them different arguments you can do like below.
import os
os.system("python script.py arg1 arg2 & python script.py arg11 arg22")
Besides subprocess.call, you can also use subprocess.Popen. Like the following
subprocess.Popen(['./script', arg1, arg2])
This works:
subprocess.call("python abc.py arg1 arg2", shell=True)
runfile('abc.py', ['arg1', 'arg2'])
This works for me :
import subprocess
subprocess.call(['python.exe', './abc.py', arg1, arg2])
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
A Python script that I want to use (called snakefood) is normally run from the commandline and takes commandline arguments, eg:
sfood /path/to/my/project
The parsing of the commandline arguments happens in a file called gendeps.py using optparse. However, I want to use the snakefood module from another script. Is there a way I can somehow mock the passing of commandline arguments to snakefood or a way of rewriting gendeps.py so that it doesn't depend on optparse anymore?
You can always assign a new list to sys.argv:
import sys
sys.argv = ['programname', '-iq', '-q', directory]
gendeps.gendeps()
optparse uses sys.argv[1:] as input when no explicit arguments have been passed in.
I just want to have some ideas to know how to do that...
I have a python script that parses log files, the log name I give it as an argument so that when i want to run the script it's like that.. ( python myscript.py LOGNAME )
what I'd like to do is to have two scripts one that contains the functions and another that has only the main function so i don't know how to be able to give the argument when i run it from the second script.
here's my second script's code:
import sys
import os
path = "/myscript.py"
sys.path.append(os.path.abspath(path))
import myscript
mainFunction()
the error i have is:
script, name = argv
valueError: need more than 1 value to unpack
Python (just as most languages) will share parameters across imports and includes.
Meaning that if you do:
python mysecondscript.py heeey that will flow down into myscript.py as well.
So, check your arguments that you pass.
Script one
myscript = __import__('myscript')
myscript.mainfunction()
script two
import sys
def mainfunction():
print sys.argv
And do:
python script_one.py parameter
You should get:
["script_one.py", "parameter"]
You have several ways of doing it.
>>> execfile('filename.py')
Check the following link:
How to execute a file within the python interpreter?
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.