python how to read data after script name - python

I am new to python and would like to give the arguments to a script as in-line arguments after the script name.
For example: given the script
mypython_script.py
I would like to launch it from terminal in the following way:
python3.4 mypython_script.py argument_1=5.0, argument_2=12.3, nome_file='out_put.dat'
I am able to read/print into terminal via the following command:
print ('Input Argument_1')
string_input= input()
Argument_1=float(string_input)
print('Argument_1 %f ' % Argument_1)
print ('Input Argument_2')
string_input= input()
Argument_2=float(string_input)
print('Argument_2 %f ' % Argument_2)
print ('Input nome_file')
nome_file= input()
print('nome_file %s ' % nomefile)
But in order to do this I have to interact with the program, my question is: how can I give to the script all the arguments in the line in which I execute it from shell?

Check out the argparse tutorial for information on how to use the argparse module. It's an easy-to-use yet powerful module for interacting with command-line arguments, setting up help messages, formatting printouts, and more.

You have to use sys.argv to retrive parameter after scripts
sys.argv[0] will give you first argument.
Please use different argument as python script_name.py arg1 arg2 arg3 arg4
If you have to use unix type argument syntext like python script arg1=val1 arg2=val2 then user argparser

Related

Python sys.argv - Get the full command line [with pipe or semicolon]

rI would like to know if it is possible to capture an entered full command line with pipe or semicolon as below:
$> python foo.py arg arg | arg arg
OR
$> python foo.py arg arg ; arg arg
Today in my attempts, sys.argv is returning only what is typed in the left side of the pipe/semicolon and the second part runs as an independent command (what is understandable, but not desired :) ).
I tried the code:
if not '\'' in sys.argv or not '"' in sys.argv:
print 'foo failed'
exit
to force the commands be quoted (and maybe to force the system to see everything as a single command line), but did not work and the second part keeps being executed after the break.
Python is not given access to those parts. Those are not part of the command arguments for Python, those are input for the shell. Pipes, quoting and semicolons are part of the shell syntax, not a command line for subprocesses that the shell starts.
The shell splits out syntax you give it, then calls Python with just the arguments addressed to the python binary. You can't retrieve the whole shell commands from subprocesses, that'd be a potential security issue.
If you want to pass on information to the Python script, you must do so in the command arguments. That means that if you must include quotes in your arguments, you must first escape them at the shell level, so they are not interpreted as shell syntax, e.g.
python foo.py arg1 '|' arg2
is then available in sys.argv as
['foo.py', 'arg1', '|', 'arg2']
where the single quotes around the | tell the shell to treat that character as argument text.
You need to consult the documentation for your specific shell environment for the details on how quoting works. For example, if you use bash, read the Bash manual section on quoting.

Pass arguments to python from bash script

I have been working on a script mixture of bash and python script. The bash script can receive unknown count input arguments. For example :
tinify.sh test1.jpg test2.jpg test3.jpg .....
After the bash receives all, it pass these arguments to tinify.py. Now I have come out two ways to do that.
Loop in bash and call python tinify.py testx.jpg
In another word, python tinify test1.jpg then python tinify test2.jpg, finaly python tinify test3.jpg
Pass all arguments to tinify.py then loop in python
But there is a problem, I want to filter same parameter for example if user input tinify.sh test1.jpg test1.jpg test1.jpg , I only want tinify.sh test1.jpg.So I think it's easier to do in second way because python may be convenient.
How can I do to pass all arguments to python script? Thanks in advance!
In addition to Chepner's answer above:
#!/bin/bash
tinify.py "$#"
within python script, tinify.py:
from sys import argv
inputArgs = sys.argv[1:]
def remove_duplicates(l):
return list(set(l))
arguments=remove_duplicates(inputArgs)
The list arguments will contain the arguments passed to python script (duplicated removed as set can't contain duplicated values in python).
You use $# in tinify.sh
#!/bin/bash
tinify.py "$#"
It will be far easier to eliminate duplicates inside the Python script that to filter them out from the shell. (Of course, this raises the question whether you need a shell script at all.)
A python program can accept any number of command line arguments, using sys.argv — just remember that sys.argv[0] is the name of the script
and actual arguments are contained in sys.argv[1:]
$ cat test_args.py
from sys import argv
prog_name = argv[0]
print('Program name:', prog_name)
for arg in argv[1:]:
print(arg)
$ python test_args.py a b 'c d'
Program name: test_args.py
a
b
c d
$
note that an argument containing spaces must be quoted according to the shell syntax.
Your file tinify.py should start with the following (if you have two arguments):
import sys
arg1, arg2 = sys.argv[1], sys.argv[2]
sys.argv[0] is the name of the script itself. You can of course loop over sys.argv. Personally, i like to pass all the arguments as json objects, so afterwards I do json.loads()

Executing a shell script with arguments from a python script

My Shell script is executed like this from the command line
./pro.sh "Argument1"
I am calling it from my python script currently like this
subprocess.call(shlex.split('bash pro.sh "Argument1"'))
How do I pass the value of Argument1 as a variable. My argument to the script can be any string. How do I achieve this?
You can use
subprocess.Popen(["bash", "pro.sh", "Argument1"])
If your string argument is multiple words, it should work fine.
subprocess.Popen(["bash", "pro.sh", "Argument with multiple words"])
As long as the multiple words are in one string in the list passed to subprocess.Popen(), it is considered one argument in the argument list for the command.
You should not use shell=True unless you have a good reason. It can be a security problem if you aren't very careful how it is used.
use subprocess to call your shell script
subprocess.Popen(['run.sh %s %s' % (var1, var2)], shell = True)

os.system command to call shell script with arguments

I am writing a python script which uses os.system command to call a shell script.I need help understanding how I can pass the arguments to the shell script? Below is what I am trying..but it wouldn't work.
os.system('./script.sh arg1 arg2 arg3')
I do not want to use subprocess for calling the shell script. Any help is appreciated.
Place your script and it's args into a string, see example below.
HTH
#!/usr/bin/env python
import os
arg3 = 'arg3'
cmd = '/bin/echo arg1 arg2 %s' % arg3
print 'running "%s"' % cmd
os.system(cmd)
If you insert the following line before os.system (...), you will likely see your problem.
print './script.sh arg1 arg2 arg3'
When developing this type of thing, it usually is useful to make sure the command really is what you expect, before you actually try it.
example:
def Cmd():
return "something"
print Cmd()
when you are satisfied, comment out the print Cmd() line and use os.system (Cmd ()) or subprocess version.

Python script argument conditional

Is anyone able to tell me how to write a conditional for an argument on a python script? I want it to print "Argument2 Entered" if it is run with a second command line arguments such as:
python script.py argument1 argument2
And print "No second argument" if it is run without command line arguments, like this:
python script.py argument1
Is this possible?
import sys
if len(sys.argv)==2: # first entry in sys.argv is script itself...
print "No second argument"
elif len(sys.argv)==3:
print "Second argument"
There are many answers to this, depending on what exactly you want to do and how much flexibility you are likely to need.
The simplest solution is to examine the variable sys.argv, which is a list containing all of the command-line arguments. (It also contains the name of the script as the first element.) To do this, simply look at len(sys.argv) and change behaviour based on its value.
However, this is often not flexible enough for what people expect command-line programs to do. For example, if you want a flag (-i, --no-defaults, ...) then it's not obvious how to write one with just sys.argv. Likewise for arguments (--dest-dir="downloads"). There are therefore many modules people have written to simplify this sort of argument parsing.
The built-in solution is argparse, which is powerful and pretty easy-to-use but not particularly concise.
A clever solution is plac, which inspects the signature of the main function to try to deduce what the command-line arguments should be.
There are many ways to do this simple thing in Python. If you are interested to know more than I recommend to read this article. BTW I am giving you one solution below:
import click
'''
Prerequisite: # python -m pip install click
run: python main.py ttt yyy
'''
#click.command(context_settings=dict(ignore_unknown_options=True))
#click.argument("argument1")
#click.argument("argument2")
def main(argument1, argument2):
print(f"argument1={argument1} and argument2={argument2}")
if __name__ == '__main__':
main()
Following block should be self explanatory
$ ./first.py second third 4th 5th
5
$ cat first.py
#!/usr/bin/env python
import sys
print (len(sys.argv))
This is related to many other posts depending upon where you are going with this, so I'll put four here:
What's the best way to grab/parse command line arguments passed to a Python script?
Implementing a "[command] [action] [parameter]" style command-line interfaces?
How can I process command line arguments in Python?
How do I format positional argument help using Python's optparse?
But the direct answer to your question from the Python docs:
sys.argv -
The list of command line arguments passed to a Python script. argv[0] is the script name (it is operating system dependent whether this is a full pathname or not). If the command was executed using the -c command line option to the interpreter, argv[0] is set to the string '-c'. If no script name was passed to the Python interpreter, argv[0] is the empty string.
To loop over the standard input, or the list of files given on the command line, see the fileinput module.

Categories