python - 如何从 bash shell 提示符运行带有句子作为命令行参数的 python 程序

标签 python linux bash shell command-line

我想运行一个 python 程序,它将一个句子作为 bash shell 提示符下的命令行参数。

我试过以下两种方式,一种有效,另一种无效,为什么会这样?两种方式都应该有效。

为什么第一种方式报错?

提前致谢

test.py 只打印参数。公司名称


sumanth@sumanth:~$ cat test.py
import os
import argparse

parser = argparse.ArgumentParser(description='')

parser.add_argument('-co',action='store',dest='co',default='aa')

results = parser.parse_args()

co = results.co

print co

sumanth@sumanth:~$ 
sumanth@sumanth:~$ 
sumanth@sumanth:~$ 
sumanth@sumanth:~$ cmd='python test.py -co "\"ABC Networks"\"'
sumanth@sumanth:~$ 
sumanth@sumanth:~$ $cmd
usage: test.py [-h] [-co CO]
test.py: error: unrecognized arguments: Networks"\"
sumanth@sumanth:~$ 
sumanth@sumanth:~$ 
sumanth@sumanth:~$ 
sumanth@sumanth:~$ 
sumanth@sumanth:~$ python test.py -co "\"ABC Networks"\"
"ABC Networks"
sumanth@sumanth:~$ 
sumanth@sumanth:~$ 

最佳答案

为什么要尝试将命令保存在 $cmd 中?如果您改用脚本,则可以使用 "$@" 传递参数:

运行测试.sh:

#!/bin/bash

python "$@"

结果:

$ ./runTest.sh test.py "ABC Networks"
Number of arguments: 3 arguments.
Argument List: ['test.py', '-co', 'ABC Networks']

否则你可以尝试使用 eval:

$ cmd='python test.py -co "ABC Networks"'
$ eval $cmd
Number of arguments: 3 arguments.
Argument List: ['test.py', '-co', 'ABC Networks']

关于python - 如何从 bash shell 提示符运行带有句子作为命令行参数的 python 程序,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22037863/

相关文章:

bash - 通过命令行将文本文件中的每一行拆分为新的文本文件

linux - 从 Bash 脚本中使用 Apache 执行 'git pull'

python - 即使 python/django 中的值相同,assertEqual 也会失败

python - Matplotlib 将所有子图的条形宽度设置为相同大小

python - 使用多处理停止 web2py 中长时间运行的操作

c - liburing/IORING_OP_PROVIDE_BUFFERS - 分配给读取操作的错误缓冲区

linux - 无法找到安装了 abrt-hook-cpp 的核心文件

python - 如何合并两个数据帧并正确索引生成的数据帧(从零开始到行数-1)

MySQL UTF8 Windows 导出 - Linux 导入

linux - 从远程服务器保持文件更新