“Python -Code im Bash -Skript” Code-Antworten

Python -Code im Bash -Skript

#!/bin/sh
python disk.py
DreamCoder

Python -Code im Bash -Skript

The simplest approach is to just save the python script as, for example script.py and then either call it from the bash script, or call it after the bash script:

#!/usr/bin/env bash
echo "This is the bash script" &&
/path/to/script.py
Or

script.sh && script.py
DreamCoder

Python -Code im Bash -Skript

You can use heredoc if you want to keep the source of both bash and python scripts together. For example, say the following are the contents of a file called pyinbash.sh:

#!/bin/bash

echo "Executing a bash statement"
export bashvar=100

cat << EOF > pyscript.py
#!/usr/bin/python
import subprocess

print 'Hello python'
subprocess.call(["echo","$bashvar"])

EOF

chmod 755 pyscript.py

./pyscript.py
Now running the pyinbash.sh will yield:

$ chmod 755 pyinbash.sh
$ ./pyinbash.sh
Exe
DreamCoder

Python -Code im Bash -Skript

#!/bin/bash
/usr/bin/python /absolute/path/to/your/disk.py
DreamCoder

Python -Code im Bash -Skript

#!/bin/bash
python3
print("Hello World")
exit()
echo "The execution is completed"
DreamCoder

Python -Code im Bash -Skript

*2 Example of the dangers of temp files. DO NOT USE THIS CODE

cat >/tmp/python-script <<END
for i in range(10):
    print(i)
END
python /tmp/python-script
If someone else creates /tmp/python-script first, this shell script won't even stop if it fails to overwrite the file. A malicious user on the system could make a harmful Python script which will run instead of the intended script.
DreamCoder

Python -Code im Bash -Skript

#!/bin/bash

PYCMD=$(cat <<EOF
from datetime import datetime

first_day_of_new_year = datetime(2022, 1, 1)

days_remaining = (first_day_of_new_year - datetime.now()).days
print('{} days remaining in this year'.format(days_remaining))
EOF
)

python3 -c "$PYCMD"
DreamCoder

Python -Code im Bash -Skript

#!/bin/bash

MYSTRING="Do something in bash"
echo $MYSTRING

python - << EOF
myPyString = "Do something on python"
print myPyString

EOF

echo "Back to bash"
DreamCoder

Python -Code im Bash -Skript

read -p "How many numbers: " n
python <<END
for i in range($n):
    print(i)
print("Literal dollar sign \$")
END
DreamCoder

Python -Code im Bash -Skript

There are ways to do this safely, but the simplest way would be to create the files in the current working directory or in a dedicated directory in the home directory.

cat >dopythonstuff <<END
...
END
python dopythonstuff
rm dopythonstuff
DreamCoder

Ähnliche Antworten wie “Python -Code im Bash -Skript”

Fragen ähnlich wie “Python -Code im Bash -Skript”

Weitere verwandte Antworten zu “Python -Code im Bash -Skript” auf Python

Durchsuchen Sie beliebte Code-Antworten nach Sprache

Durchsuchen Sie andere Codesprachen