User Tools

Site Tools


python:pythonbasicexamples

Differences

This shows you the differences between two versions of the page.

Link to this comparison view

Both sides previous revisionPrevious revision
Next revision
Previous revision
python:pythonbasicexamples [2020/02/26 15:55] – [os.path] adminpython:pythonbasicexamples [2022/10/29 16:15] (current) – external edit 127.0.0.1
Line 22: Line 22:
   * Remove (delete) the directory path<code python>   * Remove (delete) the directory path<code python>
 os.rmdir(path)</code>  os.rmdir(path)</code> 
-==== os.path ====+
 ==== os.path basic functions ==== ==== os.path basic functions ====
   * split:<code python>   * split:<code python>
Line 210: Line 210:
 print pathofexecute print pathofexecute
 </code> </code>
-===== Read and Update File =====+==== Read and Update File ====
 <code python> <code python>
 with open(filename, "rb") as f: with open(filename, "rb") as f:
Line 218: Line 218:
    with open(filename, "wb") as f:    with open(filename, "wb") as f:
       f.write(content)       f.write(content)
 +</code>
 +===== Python Command Line Arguments =====
 +refer: https://www.tutorialspoint.com/python/python_command_line_arguments.htm
 +
 +Consider we want to pass two file names through command line and we also want to give an option to check the usage of the script. Usage of the script is as follows −
 +<code bash>
 +usage: test.py -i <inputfile> -o <outputfile>
 +</code>
 +Here is the following script to test.py −
 +<code python>
 +#!/usr/bin/python
 +
 +import sys, getopt
 +
 +def main(argv):
 +   inputfile = ''
 +   outputfile = ''
 +   try:
 +      opts, args = getopt.getopt(argv,"hi:o:",["ifile=","ofile="])
 +   except getopt.GetoptError:
 +      print 'test.py -i <inputfile> -o <outputfile>'
 +      sys.exit(2)
 +   for opt, arg in opts:
 +      if opt == '-h':
 +         print 'test.py -i <inputfile> -o <outputfile>'
 +         sys.exit()
 +      elif opt in ("-i", "--ifile"):
 +         inputfile = arg
 +      elif opt in ("-o", "--ofile"):
 +         outputfile = arg
 +   print 'Input file is "', inputfile
 +   print 'Output file is "', outputfile
 +
 +if __name__ == "__main__":
 +   main(sys.argv[1:])
 +</code>
 +Now, run above script as follows −
 +  * Option1:<code bash>
 +$ test.py -h
 +</code>output:<code>
 +test.py -i <inputfile> -o <outputfile>
 +</code>
 +  * Option2:<code bash>
 +$ test.py -i inputfile
 +</code>output:<code>
 +Input file is " inputfile
 +Output file is "
 </code> </code>
python/pythonbasicexamples.1582732528.txt.gz · Last modified: 2022/10/29 16:15 (external edit)