Welcome, guest | Sign In | My Account | Store | Cart

This script checks if command-line argument 'n' has been passed; if not, it sets it to the user-defined default value.

Python, 36 lines
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
import sys

def isint(x):
	try:
		x = int(x)
		return 1
	except:
		return 0

def isarg(pos):
	try:
		temp = sys.argv[pos]
		temp = 1
	except:
		temp = 0
	return temp

def setarg(pos, val):
	if isarg(pos):
		if isint(sys.argv[pos]):
			return int(sys.argv[pos])
		else:
			return sys.argv[pos]
	else:

		sys.argv.append(str(val)) # str(val) is used, because by default all arguments are strings  
		if isint(sys.argv[len(sys.argv)-1]):
			return int(sys.argv[len(sys.argv)-1])
		else:
			return sys.argv[len(sys.argv)-1]

## usage : FileNameToProcess = setarg(1, "default.txt")

## Explanation:
##     if there is an argument at sys.argv[1], return that value;
##     if not, sys.argv[1] to "default.txt"

(I intend to write a more complex, more concise script based on the above.)

Created by Ahsan A on Thu, 4 Oct 2001 (PSF)
Python recipes (4591)
Ahsan A's recipes (1)

Required Modules

Other Information and Tasks