How create some kind of "main" class in Python

I am beginner in python. I created project with three .py files and one database file in PyCharm. But don`t understand how run my project via cmd console or something else. Do I need to create start class like "main" or what to do? How can I sent my project to another people that they may run it?

On the screen I tried run .py file via cmd Windows console screenshot of python exception

Upvotes: 0

Views: 1881

Answers (3)

Harshit Garg
Harshit Garg

Reputation: 2259

Each of your .py file is an executable. Depending on how you have coded, these files might be inter-dependent. In that case, there might be a main file(with any name, need not name it main.py, could be hello.py). So, you can run that file with python <filename>. As far as the language is concerned, there is no need to create a special class like main. Though you are free to do that.

General style it to include a statement in the end of the main file like suppose you have three files hello.py, bye.py, work.py, where

from work import *
from bye import *

def hello():
    print "Hello"

if __name__ == "__main__":
    hello()

You can run python hello.py

For sharing, you can create a zip of the folder and share that zip or you can create a git hub repository and share the github link.

The error is in opening the file. please check for spelling errors and the location of the db file

Upvotes: 0

OneCricketeer
OneCricketeer

Reputation: 191844

Your code ran.

The error seems to suggest that it's running from the src folder and trying to open a src subdirectory with a database.

Without giving absolute paths, all file references are relative to the executed script. So, just connect to the database name, not src/Contacts.db

Upvotes: 0

Lifu Huang
Lifu Huang

Reputation: 12869

Python program does not require "main function" as entry point, each line of a .py file will be executed sequentially. All you need is to type: python yourprogram.py in your console.

But on the other hand, many people choose to have a "main function" in their python program and only invoke this function when python program is run as a stand-alone script as opposed to being loaded as a module.

def main():
  # do something

if __name__ == "__main__": 
  main()

Upvotes: 2

Related Questions