1、shell脚本#
1.1 脚本执行#
1
2
3
4
5
6
7
8
|
cat > test.sh
#!/bin/bash
echo "Hello World!"
chmod u+x test.sh
./test.sh
# Hello World!
|
1
2
3
4
5
6
|
cat > test.sh
echo "Hello World!"
bash ./test.sh
# Hello World!
|
1.2 脚本传参#
- $0 脚本名
- $1 第一个参数
- $2 第二个参数…
- $@ 全部参数
- $# 输入参数个数
1
2
3
4
5
6
|
cat > plus.sh
num1=$1
num2=$2
echo "${num1}+${num2}" | bc
bash ./plus.sh 1 2
|
2、python脚本#
2.1 脚本执行#
1
2
3
4
5
6
7
|
cat > test.py
#!/usr/bin/python
print("Hello World!")
chmod u+x test.py
./test.py
|
1
2
3
4
5
|
cat > test.py
print("Hello world")
python test.py
|
2.2 脚本传参 | sys模块#
- 一般使用sys模块传参,储存在sys.argv列表里,第0个元素表示脚本名,第一个元素表示第一个参数..
1
2
3
4
5
6
7
|
cat > test.py
import sys
num1 = sys.argv[1]
num2 = sys.argv[2]
print(int(num1) + int(num2))
python test.py 1 2
|
2.3 脚本传参 | argparse模块#
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
|
import argparse
# 创建 ArgumentParser 对象
parser = argparse.ArgumentParser(description="A script to train a model and save the results.")
# 添加参数
parser.add_argument(
"-s", # 短选项(简洁)
"--save_dir", # 长选项(容易理解)
type=str,
default='path/to/there',
required=True,
help="The directory to save the trained model and the results.",
)
parser.add_argument("--eval_interval", type=int, default=1) #一般最常用形式
parser.add_argument("--pos_embed", type=bool, default=True,
help='Using Gene2vec encoding or not.')
# 解析命令行参数
args = parser.parse_args()
# 使用参数
SAVE_DIR = args.save_dir
|
长选项参数中间如果存在连字符-
,在参数解析时,会自动替换为下划线_
1
2
3
|
python script.py --save_dir "path/to/dir"
python script.py -h
|
action="store_true"
if the option is specified, assign the value True
to args.params
. Not specifying it implies False
.
1
2
3
4
5
6
7
|
import argparse
parser = argparse.ArgumentParser()
parser.add_argument("--verbose", help="increase output verbosity",
action="store_true")
args = parser.parse_args()
if args.verbose:
print("verbosity turned on")
|
1
2
3
4
5
|
python prog.py --verbose
# args.verbose → True
python prog.py
# args.verbose → False
|
3、R脚本#
3.1 脚本执行#
1
2
3
4
5
6
7
|
cat > test.r
#!/usr/bin/Rscript
print("Hello world")
chmod u+x test.r
./test.r
|
1
2
3
4
5
|
cat > test.r
print("Hello world")
Rscript test.r
|
3.2 脚本传参#
1
2
3
4
5
6
7
|
cat > test.r
args <- commandArgs(trailingOnly = TRUE)
num1=args[1]
num2=args[2]
print(as.numeric(num1)+as.numeric(num2))
Rscript test.r 1 2
|
nohup后台运行,以python脚本为例:
1
|
nohup python drug_fp.py 1> ./drug_fp.log 2>&1 &
|