Python Forum
Thread Rating:
  • 0 Vote(s) - 0 Average
  • 1
  • 2
  • 3
  • 4
  • 5
hash bang
#11
You can perhaps run this shell script at launch time: it creates a python file then uses exec to run it and the python file destroys itself in the end
#!/bin/bash

read -r -d '' SPAM << ENDOFCODE
def hi():
    print('hello world')
hi()
import os
os.remove(__file__)
ENDOFCODE

echo "$SPAM" > /tmp/spam.py
exec /usr/bin/python3 /tmp/spam.py
Obviously you can run an arbitrary python script with this. You can also improve this my using mktemp to name the python script.

EDIT: Better version:
#!/bin/bash

PYFILE=$(mktemp --suffix=.py)
cat << ENDOFCODE > $PYFILE
def hi():
    print('hello world')
hi()
import os
print('removing:', __file__)
os.remove(__file__)
ENDOFCODE

exec /usr/bin/python3 $PYFILE
EDIT: In this last version, there isn't even a temporary file
#!/bin/bash

cat << ENDOFCODE | exec /usr/bin/python3 -c "import sys; exec(sys.stdin.read())"
def hi():
    print('hello world')
hi()
ENDOFCODE
You can remove the word exec if you don't mind that your python script executes with a different pid.
Reply
#12
Here is my new bash script on this problem: it runs two python processes one after the other. The first process uses the default python interpreter. Its role is to examine the file system in order to find the best available python interpreter.

The second script runs with the best python interpreter found, and replaces the current process.
#!/bin/bash

# run first python script with default python, selects best interpreter
PYINTERP=$(python -c "import sys; exec(sys.stdin.read())" << GETPYTHON
import sys
def candidates():
    yield '/usr/bin/python3'
    yield '/usr/local/bin/python3'
    yield '/usr/bin/python'
    yield '/usr/bin/python2'
    yield '/usr/local/bin/python2'
    yield sys.executable
import os
for p in candidates():
    if os.path.exists(p):
        print(p)
        break
GETPYTHON
)

# run second python script with interpreter found, replacing current process
exec $PYINTERP -c "import sys; exec(sys.stdin.read())" << PYTHONSCRIPT
import sys
def hi():
    print('Interpreter found:', sys.executable)
    print('hello world')
hi()
PYTHONSCRIPT
Reply
#13
(Feb-20-2018, 07:13 AM)wavic Wrote: How about the script just making a call to the python code in AWS Lambda?
then it would have no effect on the system in the instance at all, and be totally useless.
Tradition is peer pressure from dead people

What do you call someone who speaks three languages? Trilingual. Two languages? Bilingual. One language? American.
Reply


Forum Jump:

User Panel Messages

Announcements
Announcement #1 8/1/2020
Announcement #2 8/2/2020
Announcement #3 8/6/2020