首页 > 解决方案 > Python 3.5:将字符串作为参数传递给子进程过程

问题描述

我在 rasbian 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.xsubprocessparameter-passing

解决方案


你可以试试:

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


推荐阅读