简体   繁体   中英

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

I want to run a python program which takes a sentence as command line arguments from the bash shell prompt.

I tried using the below two ways, one way works and the other way doesnt, why is it so? Both ways should work.

Why the first way is giving error?

Thanks in advance

test.py just prints the argument. Company Name


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:~$ 

Why are you trying to save the command in $cmd? If you use a script instead, you can then use "$@" to pass the arguments across:

runTest.sh:

#!/bin/bash

python "$@"

Results:

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

Otherwise you can try using eval:

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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