Python 3.5:将字符串作为参数传递给子流程

问题描述 投票:1回答:3

我在raspberry pi linux系统上使用python 3.5。我还是新手,但在vba中确实有一些编码经验。

我的问题是这个。以下代码行正常工作:

#working
import subprocess
chrome = "chromium-browser"
site="www.ebay.com.au"
proc=subprocess.Popen([chrome,site],stdout=subprocess.PIPE)
leaf1="leafpad"
leaf2="--display"
leaf3=":0.0"
leaf4="/home/pi/Documents/leaftxt.txt"
proc=subprocess.Popen([leaf1,leaf2,leaf3,leaf4],stdout=subprocess.PIPE)

此代码成功打开Chrome到ebay,然后是一个名为leafpad的文本编辑器,其中打开了文本文件leaftxt.txt。

但是,当我尝试从文本文件加载参数字符串时,我收到一个错误:

#not working
import subprocess
tasks="/home/pi/Documents/tasklist.txt"
try:
    f=open(tasks,"r")
except FileNotFoundError:
    print('File Not found.')
    sys.exit()
for x in f:
    x1=x.strip('\n')
    proc=subprocess.Popen([x1],stdout=subprocess.PIPE)

提出的错误如下:

    Traceback (most recent call last):    
    File "/home/pi/Documents/P3Scripts/test7.py", line 19, in <module>      
proc=subprocess.Popen([x1],stdout=subprocess.PIPE)    
    File "/usr/lib/python3.5/subprocess.py", line 676, in __init__      
restore_signals, start_new_session)   
    File "/usr/lib/python3.5/subprocess.py", line 1282, in _execute_child       
raise child_exception_type(errno_num, err_msg)  
    FileNotFoundError: [Errno 2] No such file or directory: 'chromium-browser, www.ebay.com.au'

文本文件tasklist.txt包含(我也试过没有逗号)

chromium-browser, www.ebay.com.au
leafpad, --display, :0.0, /home/pi/Documents/leaftxt.txt

两个文件似乎都在做同样的事情,但我在参数的格式化中缺少一些东西,因为它们在第二个子进程过程调用中使用。

我错过了什么/做错了什么?谢谢。

python-3.x subprocess parameter-passing
3个回答
0
投票

两者之间有区别

Popen(["foo", "bar"])        # correct: you parse arguments

Popen("foo bar", shell=True) # correct on POSIX: shell parses arguments

Popen(["foo, bar"])          # incorrect: noone parses arguments

在第一个代码段中,使用第一种形式:程序名称和每个参数作为列表的单独元素。

在你的第二个片段中,你使用第三种形式:因为你正在使用数组,Popen认为你已经分离了参数,第一个参数的全部是要执行的程序的名称。当然,不存在名为chromium-browser, www.ebay.com.au的程序。


0
投票

在第一个示例中,您传递的是四个字符串,而在第二个示例中,一个字符串包含所有四个字符串。

你应该拆分它:

x1=x.strip('\n').split(', ')

0
投票

你可以试试:

import subprocess
tasks="/home/pi/Documents/tasklist.txt"
try:
    f=open(tasks,"r")
except FileNotFoundError:
    print('File Not found.')
    sys.exit()
for x in f:
    x1=x.strip('\n').split(", ") #split_str_list is a list that contains string of single line in /home/pi/Documents/tasklist.txt
    proc=subprocess.Popen(x1,stdout=subprocess.PIPE)

您传递的字符串包含以逗号分隔的参数。 Popen不接受它。 Popen args应该是一个字符串,它必须用空格或参数序列分隔。

https://docs.python.org/3/library/subprocess.html#subprocess.Popen

© www.soinside.com 2019 - 2024. All rights reserved.