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.

asked Apr 7, 2013 at 20:14

3 Answers 3

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.

answered Apr 7, 2013 at 20:17
Sign up to request clarification or add additional context in comments.

Comments

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

answered Apr 7, 2013 at 20:18

Comments

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

answered Apr 7, 2013 at 20:21

Comments

Your Answer

Draft saved
Draft discarded

Sign up or log in

Sign up using Google
Sign up using Email and Password

Post as a guest

Required, but never shown

Post as a guest

Required, but never shown

By clicking "Post Your Answer", you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.