Jas*_*ald 5 python subprocess list output
我将一个列表从 a 传递subprocess
到父进程,并且在父进程中我想将其添加到已经存在的列表中。我这样做了:
子进程脚本.py:
def func():
list = []
list.append('1')
list.append('2')
print'Testing the list passing'
print '>>> list:',list
if __name__ == '__main__':
func()
Run Code Online (Sandbox Code Playgroud)
父脚本.py:
list1 = []
list1.append('a')
list1.append('b')
ret = subprocess.Popen([sys.executable,"/Users/user1/home/subprocess_script.py"],stdout=subprocess.PIPE)
ret.wait()
return_code = ret.returncode
out, err = ret.communicate()
if out is not None:
for line in out.splitlines():
if not line.startswith('>>>'):
continue
value = line.split(':',1)[1].lstrip()
list1.extend(value)
print 'Final List: ',list1
Run Code Online (Sandbox Code Playgroud)
但是当我执行此操作时,我没有得到所需的输出。我想要的最终列表应该是:['a','b','1','2']
。但我明白['a', 'b', '[', "'", '1', "'", ',', ' ', "'", '2', "'", ']']
哪个是错误的。我在这里做错了什么?
You are doing it wrongly.
When you do - print '>>> list:',list
. It would print -
>>> list: [1, 2]
Run Code Online (Sandbox Code Playgroud)
And when you do - value = line.split(':',1)[1].lstrip()
, value would become the string -
'[1, 2]'
Run Code Online (Sandbox Code Playgroud)
And when extending list1
with value
, each character in value would be added as a new element in list1
(because it would iterate over each element of the string, which is each character and add them to the list1
).
When creating the value , you want to remove the first [
as well as the trailed ]
and then split them based on ,
.
Example code -
value = line.split(':',1)[1].lstrip().lstrip('[').rstrip(']').replace("'",'').replace(" ",'').split(',')
Run Code Online (Sandbox Code Playgroud)
The above code is a very big hack , better would be to use ast.literal_eval
as @logc mentioned in his answer -
import ast
value = ast.literal_eval(line.split(":",1)[1].lstrip())
Run Code Online (Sandbox Code Playgroud)
But please be vary, that ast.literal_eval
would evalutate the expression and return the result, you should use it with care.
归档时间: |
|
查看次数: |
267 次 |
最近记录: |