I have a python script that looks like this:
a='{}'
From my cmdline i want to be able to pass a parameter for that value in the brackets. So:
python- my_script.py Hello World
The output would then be:
'Hello World'
Any ideas or suggestion as to how to pass a parameter on the command line in a python script when running it? I am new to python so any tips would help!
Reference here!
I'm also fairly new to Python so not 100% positive this works but assuming it does, To recreate what your searching for.
#!/usr/bin/python
import sys
print ('Number of arguments:', len(sys.argv), 'arguments.')
print ('Argument List:', str(sys.argv))
After adding the Import sys
Where your python my_script.py 'Hello World'
Note that:
my_script.py equals sys.argv[0]
'Hello World' equals sys.argv[1]
Therefore setting a = sys.argv[1] should work!
To test it try to print(a)
Also note that this will not work if your cmdline is
python my_script.py Hello World
This will treat Hello and world as two separate arguments.
Related
I'm going nuts trying to figure out how to correctly pass arguments from a shell script to python when backticks are involved.
This is my ./foo.sh
#!/bin/bash
EXEC_SCRIPT="./foo.py -c $1"
result=`${EXEC_SCRIPT}`
echo ${result}
This is my ./foo.py
#!/usr/bin/python
import argparse
ap = argparse.ArgumentParser()
ap.add_argument('-c', required=True)
args,u = ap.parse_known_args()
args = vars(args)
print ("I GOT {}".format(args['c']))
I do:
./foo.sh ABC
and I get :
I GOT ABC
Perfect.
But then I do:
./foo.sh "Hello World"
And I get:
I GOT Hello
Trying to change the bash script to:
EXEC_SCRIPT="./foo.py -c \"$1\""
Produces:
I GOT "Hello
None of this is an issue if I don't use backticks. Escaped quotes work great.
What am I missing?
What I really want is the python script should get my argument, whether its 1 word or 2 without quotes.
Further clarification: Thanks to Gordon and AK47 for making the same suggestion. It looks like the root cause is I am stuffing the command in a variable called EXEC_SCRIPT. Invoking the command directly inside the backticks works. My real script is more complex and EXEC_SCRIPT points to different values due to different conditions. What's a good way to achieve clean code which lets me figure out the right command and then invoke it at the end? Using a variable is logical, as I did, but it apparently doesn't work
I have #that other guy to thank and #Gordon Davisson for the comment clarification to the suggestion.
Modifying foo.sh to execute an array instead of a string like so:
#!/bin/bash
EXEC_SCRIPT=(./foo.py -c "$1")
result=$("${EXEC_SCRIPT[#]}")
echo ${result}
Works perfectly well!!
foo.sh
#!/bin/bash
result=`./foo.py -c "$1"`
echo ${result}
foo.py
#!/usr/bin/python
import argparse
ap = argparse.ArgumentParser()
ap.add_argument('-c', required=True)
args,u = ap.parse_known_args()
args = vars(args)
print ("I GOT {}".format(args['c']))
Testing:
MacBook-Pro:~ ak$ sh foo.sh "Hello World"
I GOT Hello World
I have a python file which contains the below code
test.py
def sum(a, b):
print(a+b)
def final():
print("Hello")
sum(10, 9)
if __name__=="__main__":
final()
Now when I run from the command line
python test.py
I get
Hello
19
Now I want to add a function say which will be called separately from the command line.How do I do it?So my updated code will be
def sum(a, b):
print(a+b)
def say():
print("Yes!!!")
def final():
print("Hello")
sum(10, 9)
if __name__=="__main__":
final()
So now I want to call the function say seperately.I tried doing this
python test.py say
But it only outputs the previous result.How can I make this work?
Start the python interpreter on the command line from the directory where your source file is. Then you can do
from test import say
say()
Edit:
Based on the comments above, you could check sys.argv to find if the module was called with "say":
import sys
if __name__ == '__main__':
if 'say' in sys.argv:
say()
else:
final()
sys.argv is a list with all the arguments the module was called with so if you from the command line run
python test.py say foo bar
then
sys.argv = ['test.py', 'say', 'foo', 'bar']
inside your program.
Your code will have to know what to do, somehow. This leaves you two alternatives:
1. The code will decide what to do based on external information:
a. Read a variable from the environment:
import os
if os.environ.get('TERM') == 'xterm-256color':
say()
else:
final()
You may set environment variables before calling the script as in:
# set the variable
$ export VARIABLE=VALUE
# Python will recognize it:
$ python -c "import os; print(os.environ.get('VARIABLE'))"
$ VALUE
b. Roll a dice:
from random import randint
if randint(0,6) > 3:
say()
else:
final()
2. You will tell the code what to do:
a. Check sys.argv (see other answers).
b. Recommended: Use the argparse library to parse commands:
import argparse
parser = argparse.ArgumentParser()
parser.add_argument("--say", help="If say, then say", action="store_true")
args = parser.parse_args()
if args.say:
say()
else:
final()
Now, from the command line run: python test.py --say
Argparse is part of the standard python library, has excellent documentation, is easy to use and read, and (in my opinion) is very flexible.
c. For somewhat larger scripts / projects, use setuptools entrypoints:
Details on this related question and this post.
I'm trying to send a parameter on jenkins and have the parameter recognized on the a python file.
Is there a command where I could do this on bash:
param = "Hello World"
param -> /usr/green/test.py
Also how does the py file know to grab the parameter?
you can pass parameters from BASH to you python script via using sys egg in the python scripts. then pass on the environment variables in the command .
PyScript
import sys
print 'Number of arguments:', len(sys.argv), 'arguments.'
print 'Argument List:', str(sys.argv)
command in BASH :
$python test.py $BUILD_ID $BUILD_URL
output :
Number of arguments: 2 arguments.
Argument List: ['test.py', '107', 'http://0.0.0.0:8080/artefact/builds/24']
You can access parameters passed to the script this way:
import sys
print sys.argv[1]
~ python test.py 'hello world'
You have to put the script's arguments after the file path separated by spaces, like this:
/usr/green/test.py arg1 arg2 arg3
to pass the value of a bash variable to the script, you have to prefix the variable name with a $ (dollar sign):
param="Hello world"
/usr/green/test.py "$param"
The list of arguments in the python script can be accessed with sys.argv. The first element in the list is the path to the script therefore the second element is the first argument.
Example
/usr/green/test.py (Python 3):
import sys
print(sys.argv[1])
bash input:
param="Hello World"
python3 /usr/green/test.py "$param"
bash output:
Hello World
Note: You have to put the variable name in quotes or Hello and World will be passed as two separate arguments to test.py.
To execute the script without the python command, you can add a #! (shebang) line:
#!/usr/bin/python3
import sys
print(sys.argv[1])
Make the script executable by typing in bash:
chmod +x /usr/green/test.py
One solution would be to print the parameter and process through a pipe with python.
Like:
read.py:
#!/usr/bin/python
import sys
pythonparams = sys.stdin.read()
# do something
then
echo "$param"|./read.py
I'm using similar approach to call python function from my shell script:
python -c 'import foo; print foo.hello()'
But I don't know how in this case I can pass arguments to python script and also is it possible to call function with parameters from command line?
python -c 'import foo, sys; print foo.hello(); print(sys.argv[1])' "This is a test"
or
echo "Wham" | python -c 'print(raw_input(""));'
There's also argparse (py3 link) that could be used to capture arguments, such as the -c which also can be found at sys.argv[0].
A second library do exist but is discuraged, called getopt.getopt.
You don't want to do that in shell script.
Try this. Create a file named "hello.py" and put the following code in the file (assuming you are on unix system):
#!/usr/bin/env python
print "Hello World"
and in your shell script, write something lke this
#!/bin/sh
python hello.py
and you should see Hello World in the terminal.
That's how you should invoke a script in shell/bash.
To the main question: how do you pass arguments?
Take this simple example:
#!/usr/bin/env python
import sys
def hello(name):
print "Hello, " + name
if __name__ == "__main__":
if len(sys.argv) > 1:
hello(sys.argv[1])
else:
raise SystemExit("usage: python hello.py <name>")
We expect the len of the argument to be at least two. Like shell programming, the first one (index 0) is always the file name.
Now modify the shell script to include the second argument (name) and see what happen.
haven't tested my code yet but conceptually that's how you should go about
edit:
If you just have a line or two simple python code, sure, -c works fine and is neat. But if you need more complex logic, please put the code into a module (.py file).
You need to create one .py file.
And after you call it this way :
python file.py argv1 argv2
And after in your file, you have sys.argv list, who give you list of argvs.
I am a newcomer to python (also very sorry if this is a newb question but) i have no idea what a command line argument is. when sys.argv is called, what exactly are the arguments? Any help with understanding this would be a great service.
Try running this program:
import sys
print(sys.argv)
You should see results similar to this:
% test.py
['/home/unutbu/pybin/test.py']
% test.py foo
['/home/unutbu/pybin/test.py', 'foo']
% test.py foo bar
['/home/unutbu/pybin/test.py', 'foo', 'bar']
% python test.py foo
['test.py', 'foo']
So, you see sys.argv is a list. The first item is the path to (or filename of) the script being run, followed by command-line arguments.
Given the command myscript.py arg1 arg2 arg3, the arguments are arg1, arg2 and arg3. sys.argv will also include the script name (i.e. myscript.py) in the first position.
Command line arguments are not specific to python.
Command line arguments are parameters you type after the script name. Eg. if you type: python test.py arg1, the first argument is arg1.
For examples, take a look at jhu.edu.
The command line arguments are the strings you type after a command in the command line, for instance:
python --help
Here --help is the argument for the python command, that shows a help page with the valid command line arguments for the python command.
In a python program, you have access to the arguments in sys.argv, so let's say you started a python script like this:
python myscript.py -x -y
When myscript.py starts, sys.argv[1] will have as value the string '-x' and sys.argv[2] will have as value the string '-y'. What you do with those arguments is up to you, and there are modules to help you easily define command line arguments, for instance argparse.
The arguments are usually used as a way of telling the program what it should do when it is run.
If I had a program named writefile.py, and I wanted the user to tell it which file to write, then I would run it with python writefile.py targetfile.txt. My sample writefile.py:
import sys
file = open(sys.argv[1], 'w') # sys.argv[0] = 'writefile.py' (unutbu's answer)
file.write('ABCDE')
file.close
After running this, I'll have a file named targetfile.txt with the contents "ABCDE". If I ran it with python writefile.py abcde.txt, I'd have abcde.txt with the contents "ABCDE".