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

Asked

Viewed 7,146 times

2

How can I call a method that is inside a.py file directly from the linux terminal, only I don’t want to enter it prompt of python For example

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

Something like the manage.py of Django/Python

  • by linux terminal, you mean running a bash?

  • that’s right, the idea is to create a arquivo.py for creating standard directories and files!

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 Django.

Here’s 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")

Examples of input and output:

python met.py metodo1 teste

Method 1 received the 'test' parameter'

python met.py metodo2 ola mundo

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

  • That’s right, thank you very much!!

1

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

Here is the argparse tutorial: https://docs.python.org/3/howto/argparse.html#id1

Now, if the script is ready,with the functions you want and you won’t touch it, nor write an auxiliary script to import the original and implement the command line switches, you can use Python with the "-c" option to run expressions separated by ";" - then, the first expression is to import your Python script, and the second, call your function.

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

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

nome=Joao
python -c "print('$nome')"

1

Edited
When I answered I focused strictly on the question itself, but then I saw in the comments that the author’s intention is to do something similar to devops or infra management using python, and then I saw that the best answer is @jsbueno and, to complement, I decided to edit my answer with an example (prototype) from 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 that 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 q at the end of the script there is a command to print the same.

~/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 the answer "original":

To illustrate 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 function foo within hello.py

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

And now the hello function:

$ python -c 'import hello; hello.hello()'
hello world!

Browser other questions tagged

You are not signed in. Login or sign up in order to post.