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


Messages In This Thread
hash bang - by Skaperen - Feb-10-2018, 02:01 AM
RE: hash bang - by Gribouillis - Feb-15-2018, 06:34 AM
RE: hash bang - by Skaperen - Feb-16-2018, 07:11 AM
RE: hash bang - by Gribouillis - Feb-16-2018, 07:59 AM
RE: hash bang - by Skaperen - Feb-17-2018, 02:12 AM
RE: hash bang - by Gribouillis - Feb-17-2018, 10:31 AM
RE: hash bang - by Skaperen - Feb-18-2018, 04:27 AM
RE: hash bang - by Gribouillis - Feb-18-2018, 06:35 AM
RE: hash bang - by Skaperen - Feb-20-2018, 03:44 AM
RE: hash bang - by wavic - Feb-20-2018, 07:13 AM
RE: hash bang - by Skaperen - Feb-22-2018, 06:06 AM
RE: hash bang - by Gribouillis - Feb-20-2018, 09:40 AM
RE: hash bang - by Gribouillis - Feb-21-2018, 08:58 AM

Forum Jump:

User Panel Messages

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