I want write a shell script that will run a Python Code stored in a shell variable $CODE
.
#!/bin/bash
python3 $CODE
But this does not work, is there any way to do this? Any help is appreciated.The program that will be run:
print("Hello World")
export CODE='print("Hello World")'
CodePudding user response:
Use the -c
option.
python3 -c "$CODE"
CodePudding user response:
python3 <<< "$CODE"
CodePudding user response:
[Python.Docs]: Command line and environment - -c <command> states:
Execute the Python code in command. command can be one or more statements separated by newlines, with significant leading whitespace as in normal module code.
Example:
[064bit prompt]> CODE='import sys;print("Hello World");print(sys.version)' [064bit prompt]> python -c "${CODE}" Hello World 3.8.10 (default, Jun 22 2022, 20:18:18) [GCC 9.4.0]
But this comes with some limitations. I'd save the code in a script and run that instead.