开发者

How can I execute python script with command line flag

I have this bit of code:

of = open("oldfile")
nf = open("newfile",'w')
for line in of:
     if len(line) &开发者_JS百科gt; 17:
             nf.write(line)

of.close()
nf.close()

and instead of specifying 17, I want to be able to use a variable put it in my scripts directory and execute it directly. If there is no flag, it could print something like 'scriptname'. If there is a flag, as there is below, it would execute the code.

$ myscriptname -l 17 oldfile newfile


See the optparse module for checking the flag and setting the value, or the newer (and better) argparse if you're willing to use 2.7+. As for putting it in my scripts directory I don't quite understand what you want exactly.


If you just want quick and dirty access to the command line parameters:

import sys
print sys.argv # <-- this is an array containing all the command line parameters

If you want some more control, you can use the optparse module.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜