I have a pthon script example.py

# !/usr/bin/python3 # -*- coding: utf-8 -*- class Foo(object): def __init__(self): self.name = "Script" def get_name(self): return self.name 

How to initialize a Foo object from a bash script and access its method? Both actions must be made from bash.

  • Neither. The shell can communicate with the process using environment variables and command line parameters. And both that and another only during start. Well, of course, you can still write to any channels or even sockets (including tcp / ip). but in all these cases it will all boil down to the fact that the external process will have to transfer a command to a already running process on a certain api, which it will process and do what it needs in this case, for example, it will create an object - Mike
  • Describe the context in which you need to pass it, maybe you misunderstood the task. - Hellseher
  • @Hellseher, I need to make it so that I can call the python methods of the shell script with commands in the order I need. It is permissible to make an object be created every time a command is typed in the console, and the corresponding object method is called. If there is a way to execute methods without creating an object, this is also appropriate. - Elefanobi
  • @Elefanobi context describe. Example - there is a script, we pass it the command line parameters and it shows, does, reads this and that . I have a structural problem with you, what should be called in from where. - Hellseher
  • there is a sh script. we pass to it the parameters necessary to initialize the object in python (parameters are not shown in the code). Initialize the object python. In the terminal (in .sh), enter the parameters for the object's methods. Call the method of the created object, pass the parameters. The method handles. We receive in sh the answer. Output to the terminal. - Elefanobi

2 answers 2

Write the code with full support for the arguments, then you can wrap it in another script, for example. bash / ash / fish / zsh / perl, etc ..

For this purpose, libraries are used to work with command line arguments.

Links

  • that's good, but how do you transfer data from python to bash? and besides, how to call methods in turn, using the results of the previous ones? - Elefanobi

The answer is found. The code should look like this.

 #!/bin/bash set -e set -u userstring="get_name()" # тут должен быть input python -c "import example; from example import Foo; m = Foo(); st = m.$userstring; print(st);" 

Script Console

Advantages:

  1. you can enter the name of the Python method in the terminal along with the positional parameters, as it would be in Python code, only without a reference to the object (name or self)

Disadvantages:

  1. The object must be created with each call.
  2. Calling methods alternately from the same object is possible only if there is no need to do input from bash again