Pass parameter from command line in python - python

I have a simple task and want to run command from the line.
E.g.
python3 -c 'print(2*2)'
The issue is when I want to invoke a function and pass parameter to it. E.g I want to lower the string 'ABC'.
I use
python3 -c 'print(x="ABC",x.lower())'
Hence my question: how could I pass string value to function when invoke python from command line?

Use sys.argv to obtain command-line arguments:
$ python3 -c "import sys; print(sys.argv[1].lower())" HELLO
hello
$

Related

passing multiple arguments to a python function from bash (in variables)

I wrote a python function called plot_ts_ex that takes two arguments ts_file and ex_file (and the file name for this function is pism_plot_routine). I want to run this function from a bash script from terminal.
When I don't use variables in the bash script in pass the function arguments (in this case ts_file = ts_g10km_10ka_hy.nc and ex_file = ex_g10km_10ka_hy.nc) directly, like this:
#!/bin/sh
python -c 'import pism_plot_routine; pism_plot_routine.plot_ts_ex("ts_g10km_10ka_hy.nc", "ex_g10km_10ka_hy.nc")'
which is similar as in Run function from the command line, that works.
But when I define variables for the input arguments, it doesn't work:
#!/bin/sh
ts_name="ts_g10km_10ka_hy.nc"
ex_name="ex_g10km_10ka_hy.nc"
python -c 'import pism_plot_routine; pism_plot_routine.plot_ts_ex("$ts_name", "$ex_name")'
It gives the error:
FileNotFoundError: [Errno 2] No such file or directory: b'$ts_name'
Then I found a similar question passing an argument to a python function from bash for a python function with only one argument and I tried
#!/bin/sh
python -c 'import sys, pism_plot_routine; pism_plot_routine.plot_ts_ex(sys.argv[1])' "$ts_name" "$ex_name"
but that doesn't work.
So how can I pass 2 arguments for a python function in a bash script using variables?
When you use single quotes the variables aren’t going to be expanded, you should use double quotes instead:
#!/bin/sh
ts_name="ts_g10km_10ka_hy.nc"
ex_name="ex_g10km_10ka_hy.nc"
python -c "import pism_plot_routine; pism_plot_routine.plot_ts_ex('$ts_name', '$ex_name')"
You can also use sys.argv, arguments are stored in a list, so ts_name is sys.arv[1] and ex_name is sys.argv[2]:
#!/bin/sh
ts_name="ts_g10km_10ka_hy.nc"
ex_name="ex_g10km_10ka_hy.nc"
python -c 'import sys, pism_plot_routine; pism_plot_routine.plot_ts_ex(sys.argv[1], sys.argv[2])' "$ts_name" "$ex_name"
You are giving the value $ts_name to python as string, bash does not do anything with it. You need to close the ', so that it becomes a string in bash, and then open it again for it to become a string in python.
The result will be something like this:
#!/bin/sh
ts_name="ts_g10km_10ka_hy.nc"
ex_name="ex_g10km_10ka_hy.nc"
python -c 'import pism_plot_routine; pism_plot_routine.plot_ts_ex("'$ts_name'", "'$ex_name'")'
For issues like this it is often nice to use some smaller code to test it, I used python3 -c 'print("${test}")' to figure out what it was passing to python, without the bother of the pism_plot.

Passing a shell variable to inline python in a shell script

I have a simple shell script where i want to be able to pass variables to some inline python i will write. For example like this
funny=879
echo $funny
python -c "
print(f"hello {$funny}")
"
However this prints
879
File "<string>", line 2
print(fhello
^
SyntaxError: unexpected EOF while parsing
(pipeline) $
Any thoughts on what i could be doing wrong? I know i am setting the variable correct because when i do echo it prints out the variable so it is definitely set correct but for some reason python script is not able to use it.
It's because you're using outer double quotes.
python -c "print(f"hello {$funny}")"
Gets turned into:
python -c print(fhello {879})
So python is passed 2 separate strings.
The inner double quotes would need to be escaped in order to get passed through to python.
$ funny=879; python3 -c "print(f\"hello $funny\")"
hello 879
Instead of messing around with quoting - if you export your variables you can access them from python using the os.environ dict.
$ export funny=879; python -c 'import os; print(os.environ["funny"])'
879
You can use the var=value command syntax and omit the export (note the lack of a semicolon)
$ funny=879 fonny=978 python3 -c 'import os; print(os.environ["funny"], os.environ["fonny"])'
879 978

How to run one line Python command in terminal?

I want to get result of a Python function in terminal.
I tried to run the command:
$ python3 -m uuid uuid.uuid4().hex
And I expect to see the output be something like: '78cbf0fadaa34ff7ac3f7b965965e207'
Unfortunately I get error:
-bash: syntax error near unexpected token `('
You were close.
The flag to run a single command is -c and not -m.
You also need to import uuid so you can use it.
You also need to use print() to actually see some output.
Finally the whole passed command has to be in quotes.
$ python3 -c "import uuid; print(uuid.uuid4().hex)"
8e79508445db4aca91bb0990529fdd89

Execute a Python statement in a Bash script

Is it possible to have Python evaluate a Python statement within a Bash shell script? I am thinking about something along the lines of perl's -e option.
The problem at hand is that I'd like to use Python's split function on a Bash string. I know it's doable in Bash alone, but I am curious.
The equivalent of perl -e is python -c:
$ python -c "import sys;print sys.argv[1].split(',')" "foo,bar,baz"
['foo', 'bar', 'baz']
One way could be pass the statement to python executable as argument of -c as below, this should be an equivalent of perl -e
python -c 'print "ABC DEF HIJ".split()'
Another possible method might be to put your python statement in a python file and pass it as argument to the command as below
exec 'python xxx.py'

Bash not recognising python command

I have this command as part of a bash script
$(python -c "import urllib, sys; print urllib.unquote(sys.argv[0])", "h%23g")
But when I run it, I get this:
-bash: -c: command not found
As though bash has missed reading the python, and is thinking -c is the name of the command. Exactly the same happens when using backticks.
How can I make bash recognise the python?
the Python command is returning the string "-c" from your $(...) structure, which bash then tries to execute.
for example
python -c "import urllib, sys; print urllib.unquote(sys.argv[0])"
prints "-c", so you are essentially asking bash to interpret $(-c), for which the error is valid.
I think you want something like the following:
$(python -c "import urllib, sys; print urllib.unquote(sys.argv[1])" "h%23g")
This will result in h#g, if this is all you have on a line then it will also attempt to run a command called h#g, so I'm assuming you are actually using this as a part of a larger command.
The issue with your version is that sys.argv[0] is the -c from the command, and urllib.unquote('-c') will just return '-c'.
From the documentation on sys.argv:
If the command was executed using the -c command line option to the interpreter, argv[0] is set to the string '-c'.
Combining that with info from the man page (emphasis mine):
-c command
Specify the command to execute (see next section). This terminates the option list (following options are passed as arguments to the command).
So, when you use -c, sys.argv[0] will be '-c', the argument provided to -c is the script so it will not be included in sys.argv, and any additional arguments are added to sys.argv starting at index 1.

Categories

Resources