Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

basic help to call python from unix

Tags:

python

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.

like image 883
yatici Avatar asked Sep 01 '26 08:09

yatici


1 Answers

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.

like image 150
shx2 Avatar answered Sep 03 '26 22:09

shx2



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!