将Python变量传递给批处理文件

时间:2017-03-21 13:05:16

标签: python batch-file subprocess python-3.6

我有一个基本的批处理文件,用于输入用户:

@echo off
set /p Thing= Type Something: 
echo %Thing%
pause

但是,我想使用Python编写的变量传递到批处理文件中。让我们说一个字符串'arg1'这只是一个基本的例子,但我仍然无法弄明白。以下代码将运行批处理,但'arg1'没有影响

import subprocess

filepath = r'C:\Users\MattR\Desktop\testing.bat'

subprocess.call([filepath, 'arg1'])

我也试过p = subprocess.Popen([filepath, 'arg1']),但批处理文件不能在Python中运行。

我搜索了网络,但是没有一个答案似乎适合我。以下是我也尝试过的一些链接:Example 1Example 2。我也尝试过其他人,但他们似乎对用户的需求非常具体。

如何开始将Python变量传递到我的批处理文件中?

2 个答案:

答案 0 :(得分:5)

如果您希望bash正常工作,您的子流程可能需要与shell一起运行

Actual meaning of 'shell=True' in subprocess

所以

subprocess.Popen([filepath, 'arg1'], shell=True)

如果你想看到输出那么:

item = subprocess.Popen([filepath, 'arg1'], shell=True, stdout=subprocess.PIPE)
for line in item.stdout:
     print line

作为进一步的编辑,这是你所追求的一个工作范例:

sub.py:

import subprocess
import random


item = subprocess.Popen(["test.bat", str(random.randrange(0,20))] , 
                         shell=True, stdout=subprocess.PIPE)
for line in item.stdout:
    print line

test.bat的

@echo off
set arg1=%1
echo I wish I had %arg1% eggs!

运行它:

c:\code>python sub.py
I wish I had 8 eggs!


c:\code>python sub.py
I wish I had 5 eggs!


c:\code>python sub.py
I wish I had 9 eggs!

答案 1 :(得分:0)

这是我设法从python到批处理文件调用变量的方式。 首先,制作一个像这样的python文件:

model {
  ssd {
    num_classes: 2
    box_coder {
      faster_rcnn_box_coder {
        y_scale: 10.0
        x_scale: 10.0
        height_scale: 5.0
        width_scale: 5.0
      }
    }
    matcher {
      argmax_matcher {
        matched_threshold: 0.5
        unmatched_threshold: 0.5
        ignore_thresholds: false
        negatives_lower_than_unmatched: true
        force_match_for_each_row: true
      }
    }
    similarity_calculator {
      iou_similarity {
      }
    }
    anchor_generator {
      ssd_anchor_generator {
        num_layers: 6
        min_scale: 0.2
        max_scale: 0.95
        aspect_ratios: 1.0
        aspect_ratios: 2.0
        aspect_ratios: 0.5
        aspect_ratios: 3.0
        aspect_ratios: 0.3333
      }
    }
    image_resizer {
      fixed_shape_resizer {
        height: 300
        width: 300
      }
    }
    box_predictor {
      convolutional_box_predictor {
        min_depth: 0
        max_depth: 0
        num_layers_before_predictor: 0
        use_dropout: false
        dropout_keep_probability: 0.8
        kernel_size: 3
        box_code_size: 4
        apply_sigmoid_to_scores: false
        conv_hyperparams {
          activation: RELU_6,
          regularizer {
            l2_regularizer {
              weight: 0.00004
            }
          }
          initializer {
            truncated_normal_initializer {
              stddev: 0.03
              mean: 0.0
            }
          }
          batch_norm {
            train: true,
            scale: true,
            center: true,
            decay: 0.9997,
            epsilon: 0.001,
          }
        }
      }
    }
    feature_extractor {
      type: 'ssd_mobilenet_v2'
      min_depth: 16
      depth_multiplier: 1.0
      use_depthwise: true
      conv_hyperparams {
        activation: RELU_6,
        regularizer {
          l2_regularizer {
            weight: 0.00004
          }
        }
        initializer {
          truncated_normal_initializer {
            stddev: 0.03
            mean: 0.0
          }
        }
        batch_norm {
          train: true,
          scale: true,
          center: true,
          decay: 0.9997,
          epsilon: 0.001,
        }
      }
    }
    loss {
      classification_loss {
        weighted_sigmoid {
                anchorwise_output: true
        }
      }
      localization_loss {
        weighted_smooth_l1 {
                anchorwise_output: true
        }
      }
      hard_example_miner {
        num_hard_examples: 3000
        iou_threshold: 0.99
        loss_type: CLASSIFICATION
        max_negatives_per_positive: 3
        min_negatives_per_image: 3
      }
      classification_weight: 1.0
      localization_weight: 1.0
    }
    normalize_loss_by_num_matches: true
    post_processing {
      batch_non_max_suppression {
        score_threshold: 1e-8
        iou_threshold: 0.6
        max_detections_per_class: 100
        max_total_detections: 100
      }
      score_converter: SIGMOID
    }
  }
}

train_config: {
  batch_size: 24
  optimizer {
    rms_prop_optimizer: {
      learning_rate: {
        exponential_decay_learning_rate {
          initial_learning_rate: 0.004
          decay_steps: 800720
          decay_factor: 0.95
        }
      }
      momentum_optimizer_value: 0.9
      decay: 0.9
      epsilon: 1.0
    }
  }
  fine_tune_checkpoint: "ssd_mobilenet_v2_coco_2018_03_29/model.ckpt"
  num_steps: 2000
  fine_tune_checkpoint_type: "detection"
}
train_input_reader {
  label_map_path: "ssd_mobilenet_v2_coco_2018_03_29/label_map.pbtxt"
  tf_record_input_reader {
    input_path: "data/train.record"
  }
}
eval_config {
  num_examples: 8000
  max_evals: 10
  use_moving_averages: false
}
eval_input_reader {
  label_map_path: "ssd_mobilenet_v2_coco_2018_03_29/label_map.pbtxt"
  shuffle: false
  num_readers: 1
  tf_record_input_reader {
    input_path: "data/val.record"
  }
}

第二,创建批处理文件,方法是转到要让python程序运行的文件夹,然后右键单击地图,然后创建新的文本文件。在此文本文件中,编写您想对变量执行的任何操作,并确保使用%...%来调用变量,如下所示:

import os
var1 = "Hello, world!"
os.putenv("VAR1", var1) #This takes the variable from python and makes it a batch one

将此文件另存为批处理文件,如下所示:file>另存为> name_of_file.bat,然后选择:另存为文件:所有文件。

然后在python中调用您的批处理文件,写:

echo %VAR1%

确保所有这些文件都在同一张图中,以便它们起作用! 到这里,这对我有用,希望我可以为某些人提供此评论,因为我搜索了很长时间才发现它是如何工作的。

PS:我也发布在另一个论坛上,所以如果您两次看到此答案,请不要感到困惑。