I know this must be a super basic question, however, I have tried finding a simple answer throughout SO and cannot find one.
So my question is this: How can I execute a python script from the command line such that I can see print statements.
For example, say I have the file test.py:
def hello():
print "hello"
If I enter the interpreter, import test.py, and then call test.hello(), everything works fine. However, I want to be able to just run
python test.py
from the command line and have it print "hello" to the terminal.
How do I do this?
Thanks!
UPDATED:
Yes, sorry, my script is actually more like this:
def main():
hello()
def hello():
print "hello"
Do I still need to call main(), or is it automatically invoked?
Add at the end of the file:
if __name__ == '__main__':
hello()
Your print statement is enclosed in a function definition block. You would need to call the function in order for it to execute:
def hello():
print "hello"
if __name__ == '__main__':
hello()
Basically this is saying "if this file is the main file (has been called from the command line), then run this code."
You have to have the script actually call your method. Generally, you can do this with a if __name__ == "__main__": block.
Alternatively, you could use the -c argument to the interpreter to import and run your module explicitly from the cli, but that would require that the script be on your python path, and also would be bad style as you'd now have executing Python code outside the Python module.
As I understand it, your file just has the following lines:
def hello():
print "hello"
The definition is correct, but when do you "call" the function?
Your file should include a call to the hello() function:
def hello():
print "hello"
hello()
This way, the function is defined and called in a single file.
This is a very "script-like" approach... it works, but there must be a better way to do it
Related
So, I made a Python file (.py) and I want to convert it into a PowerShell file (.ps1)
I tried this tool: https://github.com/x-j/ps1scriptify but every time I give it a .py file, it says:
Python script provided is not callable (does not contain a main block)
So I changed this: print("Hello, World") to this:
def main():
print("Hello, world")
main()
It still gives me the same error mentioned above.
Any help please?
That conversion script is expecting to see a block like
if __name__ == '__main__':
main()
so pop that into your script instead of just the raw call to main().
I'm using the latest spyder/anaconda (Python 3.8) software and a beginner here. When running a simple hello.py script. I get runfile('C:/Users/Raj/CODE/Python Scripts/hello.py', wdir='C:/Users/Raj/CODE/Python Scripts') but nothing else in the console or anywhere saying "Hello World".
def hello():
"""Print "Hello World" and return None."""
print("Hello World")
It can do other print type scripts just fine as I tried an old script from college.
Any function needs to be called in order to get executed. You call a function by typing it's name with the (), in your case hello()
on bottom of the python file add the call to the function hello
hello()
I have a python script that has a method that takes in a string that contains another python script. I'd like to execute that script, call a function in it, and then use that function's results in my main script. It currently looks something like this:
def executePythonScript(self, script, param):
print 'Executing script'
try:
code = compile(script, '<string>', 'exec')
exec code
response = process(param)
except Exception as ex:
print ex
print 'Response: ' + response
return response
The "process" function is assumed to exist in the script that gets compiled and executed run-time.
This solution works well for VERY simple scripts, like:
def process():
return "Hello"
...but I'm having no luck getting more complex scripts to execute. For instance, if my script uses the json package, I get:
global name 'json' is not defined
Additionally, if my process function refers to another function in that same script, I'll get an error there as well:
def process():
return generateResponse()
def generateResponse():
return "Hello"
...gives me an error:
global name 'generateResponse' is not defined
Is this an issue of namespacing? How come json (which is a standard python package) does not get recognized? Any advice would be appreciated!
import subprocess
subprocess.call(["python","C:/path/to/my/script.py"])
I would recommend against this and just use import.
This is also under the assumption that your PYTHONPATH is set in your environment variables.
This question already has answers here:
Why doesn't the main() function run when I start a Python script? Where does the script start running (what is its entry point)?
(5 answers)
Closed 6 years ago.
I have written a script that is pretty temperamental with indentation, so I decided to make functions. I'm pretty new to Python and now that I've created these functions, nothing works!
def main():
wiki_scrape()
all_csv()
wiki_set = scraped_set('locations.csv')
country_set = all_set('all.csv')
print wiki_set
I'm just wondering if this is the correct way to call functions from the main() function? I've been debating if an indentation issue is occurring within the called functions. Python seems to be very reliant on proper indentations even though it doesn't come up with an error!
Full Code - http://pastebin.com/gJGdHLgr
It sounds like you need to do this:
def main():
wiki_scrape()
all_csv()
wiki_set = scraped_set('locations.csv')
country_set = all_set('all.csv')
print wiki_set
main() # This calls your main function
Even better:
def main():
wiki_scrape()
all_csv()
wiki_set = scraped_set('locations.csv')
country_set = all_set('all.csv')
print wiki_set
if __name__ == '__main__':
main() # This calls your main function
Then run it from the command line like this:
python file_name.py
The built-in variable __name__ is the current contextual namespace. If you run a script from the command line, it will be equivalent to '__main__'. If you run/import the .py file as a module from somewhere else, including from inside the interpreter, the namespace (inside of the context of the module) will be the .py file name, or the package name if it is part of a package. For example:
## File my_file.py ##
print('__name__ is {0}'.format(__name__))
if __name__ = '__main__':
print("Hello, World!")
If you do this from command line:
python my_file.py
You will get:
__name__ is __main__
Hello, World!
If you import it from the interpreter, however, you can see that __name__ is not __main__:
>>> from my_file import *
>>> __name__ is my_file
Python doesn't call any functions on starting unless explicitly asked to (including main).
Instead Python names the files being run, with the main file being run called __main__.
If you want to simply call the main function you can use Rick's answer.
However in Python best practice it is better to do the following:
if __name__ == '__main__':
wiki_scrape()
all_csv()
wiki_set = scraped_set('locations.csv')
country_set = all_set('all.csv')
print wiki_set
This ensures that if you are running this Python file as the main file (the file you click on, or run from the command line then these functions will be run.
If this is instead used as an imported module, you can still use the functions in the script importing the module, but they will not be called automatically and thus won't interfere with the calling script.
This question already has answers here:
What does if __name__ == "__main__": do?
(45 answers)
Closed 5 months ago.
Whenever I tried to run my python script in unix nothing would happen. I'd type something along the lines
$ python script.py
and all that would be returned is
$
Now I know it isn't a problem in my code because that runs fine in idle, so I figured I needed to add something else to my code to be able to run it from the command line. In a google tutorial on python I was introduced to boilerplate code which is tacked onto the end of a function as such
def main():
print ...
etc etc
if __name__ == '__main__':
main()
And if I write a function called main and run it just like that it works fine. However when I named my function something else, anything else, it won't work. E.g.
def merge():
print ..
etc etc
if __name__ == '__merge__':
merge()
That function won't produce any output at all on the command line
Even if I just went and removed the n from the end of word main, each time it occurs in the main function above, it won't work. How does one make python functions run on the command line? and what the heck is up with python only letting functions called main be run?
Thanks!
When you run a python script from the command line, __name__ is always '__main__'.
Try something like:
def merge():
print ..
etc etc
if __name__ == '__main__':
merge()
From the Python interpreter, you have to do something more like:
>>> import script
>>> script.merge()
__name__ == "__main__"
should not be changed, if you run code from the same file you have your functions on
if __name__ == "__main__":
merge()
don't bother about that if only you're importing that module within another file
This link explains you a bith more