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.
Related
I am trying to find a way to create a Windows shortcut that executes a function from a Python file.
The function being run would look something like this (it runs a command in the shell):
def function(command):
subprocess.run(command, shell = True, check = True)
I am aware that you can run cmd functions and commands directly with a shortcut, but I would like it to be controlled by Python.
I have little experience working with Windows shorcuts, so the best I can do is show you the following:
This is what I imagine it would like like.
After a quick Google search, the only help I can find is how to make a shortcut with Python, not how to run a function from it. So hopefully what I am asking is even possible?
Generally speaking AFAIK, you can't do it, however it could be done if the target script is written a certain way and is passed the name of the function to run as an argument. You could even add arguments to be passed to the function by listing them following its name in the shortcut.
The target script has to be set up with an if __name__ == '__main__': section similar to what is shown below which executes the named function it is passed as a command line argument. The input() call at the end is there just to make the console window stay open so what is printed can be seen.
target_script.py:
def func1():
print('func1() running')
def func2():
print('func2() running')
if __name__ == '__main__':
from pathlib import Path
import sys
print('In module', Path(__file__).name)
funcname = sys.argv[1]
vars()[funcname]() # Call named function.
input('\npress Enter key to continue...')
To make use of it you would need to create a shortcut with a Target: set to something like:
python D:\path_to_directory\target_script.py func1
Output:
In module target_script.py
func1() running
press Enter key to continue...
Generalizing
It would also be possible to write a script that could be applied to other scripts that weren't written like target_script.
run_func_in_module.py:
import importlib.util
from pathlib import Path
import sys
mod_filepath = Path(sys.argv[1])
funcname = sys.argv[2]
# Import the module.
spec = importlib.util.spec_from_file_location(mod_filepath.stem, mod_filepath)
module = importlib.util.module_from_spec(spec)
spec.loader.exec_module(module)
# Call the specified function in the module.
mod_func = getattr(module, funcname)
mod_func()
To make use of this version you would need to create a shortcut with a Target: set to something like:
python D:\path_to_directory\run_func_in_module.py D:\another_directory\target_script.py func2
Note that the target_script.py would no longer need the if __name__ == '__main__': section at the end (although having one would do no harm).
I'm working on a Python project in PyCharm. For one file I would like to test parts of the code using the Python console. Problem is that the code contains a main method (used for debugging and execution) like this:
if __name__ == "__main__":
print("with main")
else:
print("no main")
When I execute that code in the Python Console (using context menu of PyCharm) then the first part of the if will be executed. I was expecting the else-part since I'm not starting the script using a Run-configuration.
Maybe you can help me how to do that.
Create file like not_main_start.py with only one line import main.py (I guess this is your main file). Run then this file. Output should show no main. __name__ would be name __main__ only if you call this file directly. If you use it as module then it will have name of the module.
This question already has answers here:
What does if __name__ == "__main__": do?
(45 answers)
Closed 6 years ago.
In some python scripts, I see this format;
def main():
#run code
if __name__ == "__main__":
main()
In other python scripts, the line if __name__ == "__main__": is not present but the code runs normally. Why have this extra redundant line when the code can run normally even without it? What is the advantage of using if __name__ == "__main__":?
This line allows you to make some functionality run by default only when you run the script as the main script (e.g. python my_script.py).
This is useful when the script may be used either as a main program or to be imported in another python module, or python shell. In the latter case you would almost certainly not want main (or other module functionality) to run on import, which is what happens by default when the interpreter loads a script.
If you'll never import this script in other code, or in a python shell then you don't need this line. However, it's good to design your code to be modular & import friendly; even what may appear as throw away scripts (e.g. plotting some numbers, parsing some logs etc.) may be useful in a larger context. Particularly in an interactive shell session, e.g. using ipython. And the cost is small: encapsulate statements in functions and add ifmain.
That is usefull when you are making a module or in general if you intend to import your scipt when running an other script. __name__ == "__main__" is true only when that script is the main script that is executed , so it avoids running subsequent code when it is ran at an import statement.
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
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