Python:输入到os.system进行拆分

时间:2018-02-25 11:36:15

标签: python linux list os.system

我希望将列表列表作为参数传递给我的python程序。当我在普通shell上做同样的事情时它工作得非常好但是当我在os.system中做同样的事情时,它只是拆分我的列表列表

import sys
import json
import os
#path=~/Desktop/smc/fuzzy/
os.system("test -d results || mkdir results")
C1=[-5,-2.5,0,2.5,5];spr1=2.5;LR1=[10,20,30,30,30]
C2=[-4,-3,-2,-1,0,1,2,3,4];spr2=1;LR2=[30,40,50,50,50]
C3=[-4,-2,0,2,4];spr3=2;LR3=[40,50,60,60,60]
arg=[[spr1,LR1,C1],[spr2,LR2,C2],[spr3,LR3,C3]]
for i in range(len(arg)):
    print ('this is from the main automate file:',arg[i])
    print('this is stringized version of the input:',str(arg[i]))
    inp=str(arg[i])
    os.system("python "+"~/Desktop/smc/fuzzy/"+"name_of_my_python_file.py "+ inp)   
    os.system("mv "+"*_"+str(arg[i])+" results")

这是它正在抛出的错误 -

('this is from the main automate file:', [2.5, [10, 20, 30, 30, 30], [-5, -2.5, 0, 2.5, 5]])
('this is stringized version of the input:', '[2.5, [10, 20, 30, 30, 30], [-5, -2.5, 0, 2.5, 5]]')
('from the main executable file:', ['/home/amardeep/Desktop/smc/fuzzy/name_of_my_python_file.py', '[2.5,', '[10,', '20,', '30,', '30,', '30],', '[-5,', '-2.5,', '0,', '2.5,', '5]]'])

在第三行中,它只是用逗号分隔列表,因此弄乱了列表。有没有办法通过这个? 而不是传递一个整齐的列表列表,如:

[2.5, [10, 20, 30, 30, 30], [-5, -2.5, 0, 2.5, 5]]

正在传递类似

的内容
[2.5,', '[10,', '20,', '30,', '30,', '30],', '[-5,', '-2.5,', '0,', '2.5,', '5]]']

我需要能够将列表列表作为参数传递给我的python程序。

1 个答案:

答案 0 :(得分:2)

  1. 不要使用$ python -m requests.help { "chardet": { "version": "3.0.4" }, "cryptography": { "version": "2.1.4" }, "idna": { "version": "2.6" }, "implementation": { "name": "CPython", "version": "3.5.3" }, "platform": { "release": "17.2.0", "system": "Darwin" }, "pyOpenSSL": { "openssl_version": "1010007f", "version": "17.5.0" }, "requests": { "version": "2.18.4" }, "system_ssl": { "version": "9081df" }, "urllib3": { "version": "1.22" }, "using_pyopenssl": true ,它已被弃用,无法使用带引号的args等组成正确的命令行...(由于from requests import async # you will need the module gevent rs = [async.get(u) for u in URL_LIST] 包含空格,您需要引用,它可以很快变得一团糟)
  2. 如果您有os.system ,请
  3. 不要使用inp

    我的提案:使用mv(python< 3.5),使用shutil.move可以评估subprocess.check_call而无需os.path.expanduser

    ~

    将参数作为参数列表传递允许shell=True在需要时处理引用。

    现在,要移动文件,请在globbed文件和import subprocess subprocess.check_call(["python", os.path.expanduser("~/Desktop/smc/fuzzy/name_of_my_python_file.py"),inp]) 上使用循环:

    check_call

    但是,从长远来看,既然你从python程序中调用python程序并且你通过了python列表,那么简单的模块导入和函数调用你会更好,直接传递列表,而不是转换为字符串,你必须在子进程中解析它们。

    本答案更适合非python子过程。

    顺便说一句,不要使用系统调用来创建目录:

    shutil

    可以用全python代码替换,OS独立:

    import glob,shutil
    for file in glob.glob("*_"+str(arg[i])):
       shutil.move(file,"results")