How to execute the method inside a .py file by the terminal linux

2

How can I call a method that is inside a .py file directly from the Linux terminal, but I do not want to enter the prompt of the python For example

[fedora@user ~]$ python arquivo.py metodo parametro

Something like% Django / Python%

    
asked by anonymous 15.08.2017 / 22:42

3 answers

2

To run a specific method within the file, the solutions proposed so far are correct, but I think what you're looking for is something more like Python Command Line Arguments , which is what is used in manage.py of django.

Here is an example of how to implement a very simple case:

import sys

def metodo1(param1):
    print("O metodo 1 recebeu o parametro '{0}'".format(param1))

def metodo2(param1, param2):
    print("O metodo 2 recebeu os parametros '{0}' e '{1}'".format(param1, param2))

qual_metodo_usar = sys.argv[1]

if qual_metodo_usar == "metodo1":
    parametro1 = sys.argv[2]
    metodo1(parametro1)
elif qual_metodo_usar == "metodo2":
    parametro1 = sys.argv[2]
    parametro2 = sys.argv[3]
    metodo2(parametro1, parametro2)
else:
    print("Metodo desconhecido")

Input and output examples:

python met.py metodo1 teste
  

Method 1 received the 'test' parameter

python met.py metodo2 ola mundo
  

Method 2 received the 'ola' and 'world' parameters

    
16.08.2017 / 14:24
1

It is best to write your program in Python so that it implements the parameters you need in the syntax most often used in command line programs. Here you mark your Python file as executable, and you can use it as you use any other command from bash.

Here is the argparse tutorial: link

Now, if the script is ready, with the functions you want and you will not move it, or write an auxiliary script to import the original and implement the command line switches, you can use Python with the option "-c" to execute expressions separated by ";" - there, the first expression is to import your Python script, and the second to call your function.

python -c "import meuarquivo; meuarquivo.minha_funcao()"   

And in the call of "my_funcao ()" you can put BASH variable prefixed with $ to pass literal parameters - but do not forget that if they are string, must be within quotation marks in the Python code. (And then you have to be careful why you have to put double quotation marks for BASH to pass your Python row as a single parameter to the Python interpreter and single quotation marks inside the parentheses

nome=Joao
python -c "print('$nome')"
    
16.08.2017 / 13:05
1
  

Edited
  When I replied I focused strictly on the question itself, but then I saw in the comments that the author's intention is to do something like devops or infra-management using python, and then I saw that the best answer is @jsbueno and, for complement, I have decided to edit my answer with an example (prototype) of argpasse that he quotes

createdir.py

#!/usr/bin/python 
import argparse
import sys

parser = argparse.ArgumentParser(
    description='Script para criacao de diretorios e arquivos padroes!')    
parser.add_argument('-v', '--verbose',action="store_true", help="verbose output" )    
parser.add_argument('-R', action="store_false",  
    help="Copia recursiva de todos os arquivos e diretorios")    
parser.add_argument('dirname', type=str, help="Diretorio a ser criado")    
parser.add_argument('filename', type=argparse.FileType('w'),
     help="Arquivo a ser criado")    

args = parser.parse_args()
print (args)

## Implemente o resto daqui em diante

Now let's make the script executable:

$ chomd +x createdir.py

After this test on the command line, because of the first line #!/usr/bin/python it is not necessary to call pyton, you can call the script directly:

$./createdir -h

Exit:

Script para criacao de diretorios e arquivos padroes!

positional arguments:
  dirname        Diretorio a ser criado
  filename       Arquivo a ser criado

optional arguments:
  -h, --help     show this help message and exit
  -v, --verbose  verbose output
  -R             Copia recursiva de todos os arquivos e diretorios

Now let's call with arguments, see at the end of the script there is a command to give a print to them.

~/createdir.py -R /home/admin arquivo1
Namespace(R=False, dirname='/home/admin', filename=<open file 'arquivo1', 
mode 'w' at 0x7f632dc47300>, verbose=False)
  

From this point on the "original" answer:

For example, let's create a file called hello.py with the following content:

def hello():
    print ('hello world!')

def foo():
    print ('bar')

Now let's call the foo function inside hello.py

$ python -c 'import hello; hello.foo()'
bar

And now the hello function:

$ python -c 'import hello; hello.hello()'
hello world!
    
16.08.2017 / 00:10