I have a simple function that simply prints "Hi!". I want to use bash to call my function, instead of lets say IDLE. However bash doesn't seem to want to print the output returned from the hi(): function.
#!/usr/bin/python
def hi():
print 'Hi!'
This doesn't print "Hi!", when I type python hi.py (or ./hi.py) into bash
However if I do not include the print statement inside of a function, but just inside the file hi.py as a lone print 'Hi!' statement; then bash does output text "Hi!" accordingly. From bash this code below outputs Hi!
#!/usr/bin/python
print 'Hi!'
From within bash, how might I make bash output the string from the function hi(): in the file hi.py?
Thanks
3 Answers 3
Assuming that you want to execute a particular function.The python executable accepts the '-c' flag to indicate that you are passing it code. So if my file (hi.py) is:
def hi():
print 'Hi!'
Then I could do:
$ python -c "execfile('hi.py'); hi()"
which pints the output
HI!
Reason
when you execute a python script you should tell it where to start.Since Hi is not a main function you need to manually call hi()
def hi():
print 'Hi!'
hi()
1 Comment
You need to do this in you hi.py:
def hi():
print 'Hi!'
if __name__ == '__main__':
hi()
Then it will work in bash:
#!/bin/bash
python hi.py
3 Comments
Are you calling the function in your python script? In order to get the print statement in your function to be activated you actually need to call the function. For example running python test.py for this file prints "Hi!"
# Program named test.py
def output():
print('Hi!')
output() # Calling the output function which will cause a print statement
Also calling this python file in bash works also. For example calling bash call.sh for this script worked and printed "Hi!" to the command line
#!/bin/bash
# Script to call python file
python test.py
hi()at the end of your python script. (this is frequently done in anif __name__ == '__main__':suite...)