简体   繁体   中英

passing sentence as a argument in subprocess command

I am executing python script inside another script and want to pass two arguments to it

lines = [line.strip('\n') for line in open('que.txt')]
for l in lines:
    print 'my sentence : '
    print l
    #os.system("find_entity.py")  //this also does not work
    subprocess.call(" python find_entity.py l 1", shell=True) //this works but l does not considered as sentence which was read

what is the correct approach?

update:

lines = [line.strip('\n') for line in open('q0.txt')]
for line_num, line in enumerate(lines):
    cmd = ["python", "find_entity.py", line]
    subprocess.call(cmd, shell=True)

then it goes to python terminal

You can use one of string substitution mechanics:

Or, in case with subprocess library you should pass arguments as list to call function:

subprocess.call(["python", "find_entity.py", line, str(line_num)])

Look at line and line_num variables — they pass without any quotes, so they would be passed by value. This solution is recommended, because it provides more clean and obvious code and provide correct parameter's processing(such as whitespace escaping, etc).

However, if you want to use shell=True flag for subprocess.call , solution with list of args will not work instead of string substitution solutions. BTW, subprocess and os provides all shell powerful options: such as script piping, expanding user home directory(~), etc. So, if you will code big and complicated script you should use python libraries instead of using shell=True .

you need the contents of variable l (I renamed it to line), not the string literal "l"

for line_num, line in enumerate(lines):
    cmd = ["python",
           "find_entity.py",
           line,
           str(line_num)]
    subprocess.call(cmd, shell=True)

If you already have the command name and its arguments in separate variables, or already in a list, you almost never want to use shell=True . (It's not illegal, but its behavior is undocumented and generally not what is wanted.)

cmd = ["python", "find_entity.py", line]
subprocess.call(cmd)

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