PyCharm: execute in Python console - python

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.

Related

calling another python script in the main file does not execute

I have two main python scripts in my project:
sftpConnector.py and fileIterator.py
sftpConnector.py establishes connection to an SFTP server and downloads some file, it however does not call any other script. It has only function: establisher()
While, fileiterator.py also has one function iterator() it calls two other scripts: folderGenerator.py and dataProcessor.py()
When independently called, both the scripts, sftpConnector.py and fileIterator.py execute properly without any issues, however, when I try to create a main.py file to call these two scripts one after the other, it does not work.
The main.py looks like this:
import sftpConnector
import fileIterator
if __name__ == 'main':
folder_name = input('File name:\n')
print('folder_name')
sftpConnector.establisher(folder_name)
fileIterator.iterator(folder_name)
This main.py file runs the first script and function, sftpConnector.establisher(folder_name) however it does not even go inside the second script. I am not sure what's going on here.
Also, not sure if this will help, but neither of the script are returning anything.
Your run guard should be
if __name__ == "__main__":
That’s how to ensure that your code only runs if run as a module (versus being imported). You accidentally checked for the wrong name (“main”) and I’m guessing that’s why the code in your if block isn’t running. It’s an easy mistake to make as it’s easy to assume that __name__ refers to the name of your file when you run your script directly, but it doesn’t; it refers to the environment where the toplevel code is run. The line if __name__ == '__main__': is asking the question: “Is this script the toplevel one?”

AP Scheduler not running - "func must be a callable or a textual reference to one"

I am trying to run a script that pulls data from online sources and then emails it to me at specified times. The idea is to run this script from another Python script which uses APScheduler to run the initial script. The reason I wanted to create 2 scripts is because I want to use something like cx_freeze to make an exe file out of the 2nd script which will run in the background of my pc so as not to have to have my IDE open all the time.
My code in the 2nd script looks as follows:
from apscheduler.schedulers.blocking import BlockingScheduler
import initial_script
import os
if __name__ == '__main__':
scheduler = BlockingScheduler()
scheduler.add_job(initial_script, trigger='cron', day_of_week='mon-fri', hour='18', minute='30')
print('Press Ctrl+{0} to exit'.format('Break' if os.name == 'nt' else 'C'))
try:
scheduler.start()
except (KeyboardInterrupt, SystemExit):
pass
The 'initial_script' is the main python file that actually provides the information I need. The APScheduler code I mostly used from the Github repo here and then I consulted this link to better understand the purpose for using the __name__ = '__main__' code (which I have a feeling is the problem). In the 'initial_script' file I have not used __name__ = '__main__' anywhere.
I have made sure that both files are saved as .py formats - initially I attempted to run the scripts from .py into jupyter notebooks .ipynb but that caused more issues.
The code from the 'initial_script' does run as I am receiving the email when I run it from the 2nd script but the scheduler/trigger gives me an error and does not run.
The error I get now is as follows: TypeError: func must be a callable or a textual reference to one
Please can you assist in explaining what I am doing wrong?
The add_job() method requires that you pass it a callable. You're passing a module and modules cannot be called (you can't do initial_script()). Maybe try passing it a function that is defined in that module?

Why doesn't IDLE need 'if __name__ == "__main__": to run a test case, but PyCharm does?

I'm practicing working with unittest, and I tried the following in PyCharm:
import unittest
from format_name import name_formatted
class TestName_formatted(unittest.TestCase):
"""practice with unittest"""
def test_name(self):
"""Testing name_formatted function"""
formatted_name = name_formatted("mike", "Cronin")
self.assertEqual(formatted_name, "mike Cronin")
unittest.main()
After research, I saw that it was written like this:
if __name__ == "__main__":
unittest.main()
And suddenly it worked perfectly. HOWEVER, the reason I wrote it that way, without the if statement, is because that's how I learned it from "Python Crash Course" which uses GEANY and IDLE for its example code. And sure enough, in both of those programs, you don't need the if statement.
Why is it that in one IDE the code doesn't work and in the others it does?
You are running the code in PyCharm as if it were a normal Python application; which is why you need the if __name__ == '__main__' conditional. This is also best practice when writing modules (files) that can be imported or run at the command line - the case with unit tests.
PyCharm is basically trying to do python your_file_name.py
The reason IDLE doesn't need this is because IDLE is running the application by first loading the file in the Python shell.
What IDLE is doing is:
python
>>> import your_file_name
By doing so, the code is automatically evaluated, the function is called and thus the test runs.
I would also suggest reading the documentation on testing in PyCharm's manual as testing is something PyCharm has extensive support for. In that link you'll also notice the default stub (or template) for a sample test case already has the if __name__ == '__main__' check:

Why is my Python function not being executed? [duplicate]

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.

Call a python main from another python script

I have been giving some huge command line tool from a colleague. The main reads a bunch of arguments, parses those using the elegant import OptionParser later on and does the job.
if __name__ == '__main__':
main(sys.argv)
I can either dig into the code and copy paste loads of code, or find a way to use a "command line" call from my python script. I guess the second option is preferrable as it prevents me from randomly extracting code. Would you agree ?
You don't need to do cut and paste or launch a new Python interpreter. You should be able to import the other script.
For example, if your colleague's script is called somescript.py you could do:
import somescript
args = ['one','two']
somescript.main(args)

Categories

Resources