3

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.

yatici
  • 557
  • 4
  • 11
  • 21

3 Answers3

7

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.

Community
  • 1
  • 1
shx2
  • 61,779
  • 13
  • 130
  • 153
1

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

Pavel Anossov
  • 60,842
  • 14
  • 151
  • 124
1

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).

Francis Avila
  • 31,233
  • 6
  • 58
  • 96