Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Passing a Python Variable to Batch File [duplicate]

I have a basic batch file that takes user input:

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

However, I'd like to use a variable written in Python to pass into the batch file. Let's say just a string 'arg1' This is just a basic example, but I still cannot figure it out. The below code will run the batch process, but 'arg1' has no impact

import subprocess

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

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

I have also tried p = subprocess.Popen([filepath, 'arg1']) but the batch file does not run in Python.

I have searched the web and SO, but none of the answers seem to work for me. Here are some links I've also tried: Example 1, Example 2. I've also tried others but they seem fairly specific to the user's needs.

How do I start passing Python variables into my batch files?

like image 769
MattR Avatar asked Sep 25 '26 03:09

MattR


1 Answers

Your subprocess likely needs to run with a shell if you want bash to work properly

Actual meaning of 'shell=True' in subprocess

so

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

If you want to see the output too then:

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

As a further edit here's a working example of what you're after:

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!

running it:

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!
like image 153
Keef Baker Avatar answered Sep 27 '26 20:09

Keef Baker