🔒 Closed How to Run Python inside a Bash File

Status
Not open for further replies.

PHC-TheGlock

Forum Master
Ok, I'm gonna share this simple trick but helpful for bash Scripters there
You need:
  • Python or Any Versions you want​
  • Bash (ofcourse)​

Were using what we called EOF trick.. i always use this trick everytime i'm creating Bash Scripts its super helpful

Now our objective here is to Run Python inside in Bash File, Heres the Example of Usage:

Sample File: python.sh
Bash:
#!/bin/bash
read -p 'Enter Your Name: ' name
sudo python3 <<EOF
import datetime
now = datetime.datetime.now()
print ("Your Name: $name")
print ("Current date and time:", now.strftime("%Y-%m-%d %H:%M:%S"))
EOF

Now the Explanation:
#!/bin/bash
in the start of Script is called Shebang it is used for identifying what type of Shell or Program you want to Execute the entire file when it became an Executable File.. This is Ignored when theres specific program presented on your command, Ex. (bash <name of file>)

read
command, Read the Manual You do not have permission to view the full content of this post. Log in or register now.

sudo python3 sudo means super user do which is used for granting something in root and python3 is the program were using.

<<EOF
<insert python codes>
EOF
The special symbol << precedes the limit string, This has the effect of redirecting the output of a command block into the stdin of the program or command.

You can insert a Variable there because stdin is not supporting ARGS or any Interactive Inputs

Now Execute it:
Bash:
chmod +x python.sh
./python.sh

Output:
Code:
Your Name: LOL
Current Date and Time:  <current date>

OKAY, thats pretty much it see you again in my new thread
Follow me For more Linux Tutorials
-
PHC-TheGlock

TIPS: If di kayo marunong mag Bash Scripting, Just Learn the basics. CD, LS, SED, AWK, GREP and others.... then magkakaidea na kayo sa mga Logical Conditions
 
bossing, bakit kelangan pa may embedded python code (at sudo)? hindi ba mas simple kung ganito:


Bash:
#!/bin/bash

read -p "Enter your name: "
echo "Your name is: ${REPLY}"
echo "Current date and time is: $(date)"
 
bossing, bakit kelangan pa may embedded python code (at sudo)? hindi ba mas simple kung ganito:


Bash:
#!/bin/bash

read -p "Enter your name: "
echo "Your name is: ${REPLY}"
echo "Current date and time is: $(date)"
This is for python tutorial, not bash scripting. Kung may bash ka na gagamit ng python, this are the examples on how to use it.
 
Status
Not open for further replies.

About this Thread

  • 6
    Replies
  • 1K
    Views
  • 5
    Participants
Last reply from:
xLynx

Trending Topics

Online now

Members online
1,261
Guests online
7,350
Total visitors
8,611

Forum statistics

Threads
2,327,973
Posts
29,238,949
Members
1,161,367
Latest member
seasick515
Back
Top