如何将数组从python传递到shell脚本并执行它?

时间:2016-05-25 20:21:25

标签: python arrays bash

我有一个数组valgrind,它是在python脚本中定义的。我试图将此数组传递给shell脚本“arraytest”并从python本身执行它。我正在尝试使用以下代码,但它似乎无法正常工作:

private void downloadImage(File file) {
    final Uri uri = Uri.fromFile(file);
    Handler uiHandler = new Handler(Looper.getMainLooper());
    uiHandler.post(new Runnable() {
        @Override
        public void run() {
          Picasso.with(NewImageProcessingService.this).load(uri).transform(new ImageLoadingUtil.DecreaseQualityTransformation(imageQuality)).into(NewImageProcessingService.this);
        }
    });
}
@Override
protected void onHandleIntent(Intent intent) {
    File file = (File) intent.getSerializableExtra(KEY_IMAGE_FILE);
    imageQuality = ImagesUtils.IMAGE_QUALITY
            .values()[intent.getIntExtra(IMAGE_QUALITY, ImagesUtils.IMAGE_QUALITY.DEFAULT.ordinal())];
    downloadImage(file);
}

shell脚本的内容是:

HSPACE

1 个答案:

答案 0 :(得分:4)

简单的答案是将每个数组条目作为文字argv条目传递:

subprocess.call(['./arraytest'] + [str(s) for s in HSPACE], shell=False)

... ...之后

#!/bin/bash
printf 'hspace array entry: %q\n' "$@"

另一种方法是在stdin上将数组作为NUL分隔的流传递:

p = subprocess.Popen(['./arraytest'], shell=False, stdin=subprocess.PIPE)
p.communicate('\0'.join(str(n) for n in HSPACE) + '\0')

...而且,在你的shell中:

#!/bin/bash
arr=( )
while IFS= read -r -d '' entry; do
  arr+=( "$entry" )
done

printf 'hspace array entry: %q\n' "${arr[@]}"