0

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")'
1
  • You should have gotten an error message with your approach, something like "can't open file ....". Commented Aug 22, 2022 at 10:32

3 Answers 3

1

Use the -c option.

python3 -c "$CODE"
Sign up to request clarification or add additional context in comments.

Comments

1
python3 <<< "$CODE"

Comments

1

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

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.