简体   繁体   中英

Running a python program stored in a shell variable

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")'

Use the -c option.

python3 -c "$CODE"

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

python3 <<< "$CODE"

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM