Python Popen freezes but same command in windows cmd window works fine

I am pulling my hair out here. I am creating a process that I need for feedback in Python.

When I run the command in a cmd window it works fine, but when I try to run it through Python the terminal hangs.

p = subprocess.Popen(startcmd, stdout=subprocess.PIPE, stderr=subprocess.PIPE)
(out, err) = p.communicate()

      

Where startcmd

is the string that, when printed to the Python console, looks like this:

"C:/Program Files/GRASS GIS 7.2.1/grass72.bat" --version

      

If I copy and paste this into CMd Windows, it displays version information and returns control to the command line about a second later, but in Python it hangs.

I have to point out if I replace the string startcmd

with something like "dir"

or even "python --version"

, it works great!

Optional: I tried shell=True

, this has the same result.

In addition: . I tried sending the cmd and arguments through an array as suggested in the answer below, which states that shell=False

, but that hangs too.

Optional: I added the GRASS path to the PATH system so that now I can just call grass72 --version

in the CMD window to get the result, however this also still hangs in Python but works fine in cmd.

Optional: I created a basic .bat file to test if the .bat files are working with Python, this is what I created:

@echo off
title Test Batch Script
echo I should see this message

      

This works great in both cmd and Python.

Found a problem but not resolved!

So, I am running a script that starts a process using subprocess.Popen

using Python 3.6. The generated .bat file runs a Python script using the 2.7-based version of Python supplied with GRASS:

%GRASS_PYTHON% "\BLAH\BLAH\grass72.py"

      

Interestingly, if I run the subprocess.Popen

script with Python 2.7, it works fine. Aha, you might think decided! But that doesn't solve my problem - because I really need Python 3.6 to start the process, and also why does it matter which version of Python runs the batch file? The new Python script that is spawned runs from Python 2.7 anyway.

Since I started redirecting stdout, I see there is an error when I use Python 3.6 to start the process:

 File "C:\ProgramData\Anaconda3\lib\site.py", line 177
    file=sys.stderr)
        ^
SyntaxError: invalid syntax

      

Notice his return to Anaconda3! Even though it is run using python.exe from version 2.7!

+3


source to share


2 answers


Try the following:



p = subprocess.Popen(startcmd, stdout=subprocess.PIPE, stderr=subprocess.PIPE, shell=True)

      

0


source


You do not specify shell=True

in your arguments Popen

. The recommended use in this case is to specify a sequence of arguments instead of a string. Therefore, you must set startcmd

equal ["C:/Program Files/GRASS GIS 7.2.1/grass72.bat", "--version"]

.



0


source







All Articles