How to load Python script and run custom code from the terminal in the single command?

Question:

Let’s say I have a script called device.py which contains code like this:

class Simulator():
    def run():
        print('Running...')

From the shell script, I want to:

  1. Open a new tab in the terminal.
  2. Load this script to Python console.
  3. Create Simulator instance and call its run() method. I cannot add this additional code to device.py script itself.

I imagine it should look like this:

SIMULATOR_DIR="$(pwd)/directory_to_script/"
gnome-terminal --working-directory=$SIMULATOR_DIR --tab -- bash -c "python -i device.py -c "Simulator().run()"" --title="Simulator (device)";

Anyway, while the script gets loaded to the interactive shell, it does not execute custom code provided with the -c flag.

How do I load Python script and execute custom Python code in the single command?

Asked By: Karolis S.

||

Answers:

Supposing you have a class Simulator defined inside the device.py file, one thing you can do in order to execute methods on that class using an inline command is adding an import statement to your command.

You would then run:

python3 -c "from device import Simulator; Simulator().Run()"

Even though I don’t know much about your specific problem, I would suggest you to reconsider your approach because, even if it works, it is generally not a good pattern to execute python scripts in that way.

Answered By: canta2899
Categories: questions Tags: ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.