簡體   English   中英

如何從bash shell提示符中將sentiance作為命令行參數運行python程序

[英]How to run python program with a sentance as a command line arguments from bash shell prompt

我想運行一個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中? 如果改用腳本,則可以使用“ $ @”在以下參數之間傳遞參數:

runTest.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']

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM