yatici
yatici

Reputation: 577

basic help to call python from unix

Hi I am pretty new to python so I have been playing around with it. I recently created 2 files for some process I am working on which seems to be working while running python but doing nothing when write python name.py argv at the unix command line. It is probably something basic and I would appreciate some help. 1st file (make_dir.py)

import os
import sys

def main():
    directory = sys.argv[1]
    if not os.path.exists(directory):
      os.makedirs(directory)

at unix terminal I write

python make_dir.py /home/user/Python/Test/

result: Test folder is not created.

the second file has probably the same issue. 2nd file directory.py

import sys
import os

def main():
  os.chdir(sys.argv[1])
  File = open(sys.argv[2] , 'w')
  File.write(sys.argv[3])
  File.close()

at unix terminal:

python directory.py /home/user/Python/TEST/ a.log "this is a test"

a.log is not created. If I got some error messages I probably could figure it out but no messages. Any help is much appreciated.

Upvotes: 3

Views: 342

Answers (3)

Francis Avila
Francis Avila

Reputation: 31631

Python is not C and def main is not magic. There is no predefined execution entry point for Python programs. All your code is doing is defining a main function (not running it), so Python defines main and then stops (as you requested).

You must call main() explicitly if you want it to execute. You should use this idiom:

if __name__ == '__main__':
    main()

__name__ is a magic variable created at the module level that contains the module's name. If __name__ is '__main__', it means the current module was not imported but was run directly. This idiom allows you to use a Python file as both a module (something you can import--where main() should not automatically run) and as a script (where main() should run automatically).

Upvotes: 1

Pavel Anossov
Pavel Anossov

Reputation: 62908

You are not actually calling main. Simply adding main() at the end of script would suffice, but usually this idiom is used:

if __name__ == '__main__':
    main()

This would call main if the script was executed directly, and not just imported from another module.

See executing modules as scripts

Upvotes: 1

shx2
shx2

Reputation: 64318

You're defining a function called main, but never call it. Do:

import os
import sys

def main():
    ...

if __name__ == '__main__':
    main()

See here for more details about this idiom.

Upvotes: 7

Related Questions