简体   繁体   English

Python:将参数传递给脚本

[英]Python: pass arguments to a script

I have a working code to print random lines from a csv column. 我有一个工作代码可以从csv列中打印随机行。

#!/usr/bin/python

import csv   

import random 

**col**=2

with open('<filename>','r') as f:
        reader=csv.reader(f)
        data=[row[col] for row in reader]
    from random import shuffle
    shuffle(data)
    print '\n'.join(data[:**100**])
    f.close();

I want to paramaterize this script. 我想将此脚本参数化。 by passing , position (col) & sample (eg 100 values) 通过,位置(col)和样本(例如100个值)

I am unable to find a decent tutorial which would explain this. 我找不到合适的教程来解释这一点。 any thoughts ? 有什么想法吗 ?

You can use the sys module like this to pass command line arguments to your python script. 您可以像这样使用sys模块将命令行参数传递给python脚本。

import sys

name_of_script = sys.argv[0]
position = sys.argv[1]
sample = sys.argv[2]

and then your command line would be... 然后您的命令行将是...

./myscript.py 10 100 ./myscript.py 10100

Use argparse module: 使用argparse模块:

The argparse module makes it easy to write user-friendly command-line interfaces. argparse模块使编写用户友好的命令行界面变得容易。 The program defines what arguments it requires, and argparse will figure out how to parse those out of sys.argv. 该程序定义了所需的参数,而argparse将找出如何从sys.argv中解析这些参数。 The argparse module also automatically generates help and usage messages and issues errors when users give the program invalid arguments. argparse模块还会自动生成帮助和使用消息,并在用户为程序提供无效参数时发出错误。

It's pretty powerful: you can specify help messages, make validations, provide defaults..whatever you can imagine about working with command-line arguments. 它非常强大:您可以指定帮助消息,进行验证,提供默认值..无论您想到如何使用命令行参数。

import argparse

parser = argparse.ArgumentParser()
parser.add_argument("-p", "--position", type=int)
parser.add_argument("-s", "--sample", type=int)

args = parser.parse_args()
col = args.position
sample = args.sample

print col
print sample

Here's what on the command-line: 这是命令行上的内容:

$ python test.py --help
usage: test.py [-h] [-p POSITION] [-s SAMPLE]

optional arguments:
  -h, --help            show this help message and exit
  -p POSITION, --position POSITION
  -s SAMPLE, --sample SAMPLE

$ python test.py -p 10 -s 100
10
100
$ python test.py --position 10 --sample 100
10
100

Speaking about the code you've provided: 谈到您提供的代码:

  • unused import random statement 未使用的import random语句
  • move from random import shuffle to the top of the script from random import shuffle移到脚本顶部
  • no need to call f.close() (especially with ; ) - with handles closing the file automagically 无需调用f.close() (尤其是; )- with句柄自动关闭文件

Here's how the code would look like after the fixes: 修复后的代码如下所示:

#!/usr/bin/python
import argparse
import csv
from random import shuffle


parser = argparse.ArgumentParser()
parser.add_argument("-p", "--position", type=int)
parser.add_argument("-s", "--sample", type=int)

args = parser.parse_args()

with open('<filename>', 'r') as f:
    reader = csv.reader(f)
    data = [row[args.position] for row in reader]
    shuffle(data)
    print '\n'.join(data[:args.sample])

Thanks Guys. 多谢你们。

I could not install argaprse due to lack of permission - meanwhile. 由于缺少权限,我无法安装argaprse-同时。

Here's the solution- 这是解决方案-

#!/usr/bin/python

import csv   # This will help us reading csv formated files.
import sys
import optparse #import optparse

from random import shuffle

parser=optparse.OptionParser()

# import options

parser.add_option('-f','--filename',help='Pass the csv filename')
parser.add_option('-p','--position',help='column position in the file',type=int)
parser.add_option('-s','--sample',help='sample size',type=int)

(opts,args) = parser.parse_args() # instantiate parser


# Program to select random values

with open('<filepath>'+opts.filename,'r') as f:
        reader=csv.reader(f)
        data=[row[opts.position] for row in reader]

        shuffle(data)

        #print '\n'.join(data[:opts.sample])

# create o/p file
file=open("<opfilename>.txt","w")
file.write('\n'.join(data[:opts.sample]))
file.close()

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM