Python input is restricted when executed from a batch file within a conditional statement and following a timeout period

Here is a simple working example:

test.bat:

@echo off
if 0==0 (
  timeout 3
  python test.py
)

test.py:

input('press ENTER to exit')

In cmd.exe:

call test.bat
> Waiting for 0 seconds, press a key to continue ...
> press ENTER to exit_

However, the script gets stuck at the input statement. If I keep pressing enter, it will eventually raise an exception:

Traceback (most recent call last):
  File "test.py", line 1, in <module>
    input('press ENTER to exit')
OSError: [WinError 8] Not enough storage is available to process this command

This issue occurred on Windows 7 SP1 while testing with various Python versions:

  • Python 3.6 (64-bit)
  • Python 3.6 (32-bit)
  • Python 3.5 (32-bit)
  • Python 2.7 (32-bit) - in this case, the script remains stuck without raising an exception

If anyone can replicate this problem or has any insights into what might be causing it, please let me know!

Answer №1

The issue can be replicated on Windows 7 using Python 3.6.5 64 bit.

Here are a few alternatives to work around the problem with timeout:

@echo off
if 0==0 (
  echo Pause for 3 seconds
  ping -n 3 localhost >nul
  python test.py
)
exit /b

This method utilizes ping, which does not cause any issues.

@echo off
if 0==0 (
  timeout 3
  call :run_python test.py
)
exit /b

:run_python
python %*
exit /b

With this approach, a label named :run_python is used, allowing the interpreter to execute Python code outside of the parentheses. Any arguments provided after calling the label will be forwarded to python.

Answer №2

Indeed, the behavior you noted can be replicated on Windows 7 using Python 2.6 and Python 2.7, but not on Windows 10 with Python 2.7. The differences in file sizes of timeout.exe between Windows 7 and Windows 10 indicate changes to that command.

It appears that timeout may manipulate the file pointer in the STD_IN stream (handle 0), especially when adjusting the countdown display (referencing this thread: Clear a line/move the cursor, using the Timeout command or similar).

The issue is not limited to interactions with the if command; it arises as soon as both timeout and the Python script call are within the same block of code:

(
    timeout 3
    python test.py
)

A similar problem occurs when they are in the same line:

timeout 3 & python test.py

However, if these two commands are separated onto different lines without parentheses, they function correctly:

timeout 3
python test.py

Replacing the timeout command with pause, which also reads from STD_IN, resolves the issue smoothly:

(
    pause
    python test.py
)

Alternatively:

pause & python test.py

michael_heath provided a helpful workaround in his answer utilizing ping. Nevertheless, unlike timeout, this method lacks the ability to be stopped by a key press (making it comparable to timeout 3 /NOBREAK).

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

I have programmed my Python discord bot to interact and respond to commands through direct messages

After dedicating two weeks to developing a discord bot, I recently discovered that commands can be activated in direct messages. I'm concerned that this could potentially enable users with lower roles to interfere with other servers. Does anyone have ...

Python Problem: Frustrating StaleElementReferenceException

I am facing issues while using Selenium for a simple scraping task. The code is throwing StaleElementReferenceException randomly during execution, resulting in incomplete data retrieval. Despite experimenting with various waits in Selenium, I have not bee ...

Arrange a JSON file by organizing a key located within an array of dictionaries using Python

Here's a structure that I am working with: [{ "name": "apple", "price": "5.0", "record": [ { "id": "008", "time": 1465689600 } ] },{ "name": "banana", "price": "9.0", "record": [ ...

Combining a JSON file and a CSV file into a pandas dataframe for analysis

I have a JSON file with geographic data that includes information on population counts for different areas represented by WK_CODE. { "type" : "FeatureCollection", "name" : "NBG_DATA.CBSWBI", "feature ...

What is the method in Python to utilize a range of numbers within a variable in an f-string, allowing them to be inserted and executed sequentially?

As a newcomer to the coding realm, I'm seeking some assistance with a Selenium and Python project. I've been unable to locate any useful resources thus far. Is it feasible to define variables in an f-string as a range of numbers that are then ins ...

Finding and saving several elements using selenium

In my current project, I am trying to locate and save the positions of certain elements so that a bot can click on them even if the page undergoes changes. While researching online, I found suggestions that storing the location of a single element in a var ...

Python's ability to nest objects within other objects allows for complex data

I had an interesting experience during a quiz in my class. One of the questions stated that an object in Python cannot contain other objects within itself, which didn't quite add up to me. After all, why couldn't there be a class table and a clas ...

Python Google Colab raised a ValueError indicating that there are insufficient values to unpack, with an expected 4 values but only receiving 2

Just starting out with Python in Google Colab and need to complete my project on image classification using the KNN algorithm. I could really use some help fixing this code. Thank you! # Importing the dataset dataset = ('/content/dataset/Validation/&a ...

What is the best way to broadcast messages to multiple clients using Flask-SocketIO?

Currently, I am diving into the world of Flask-SocketIO with a simple chat application in mind. However, I've encountered an issue where messages are not being received by anyone except for the user in the browser. Here's the Python/Flask code sn ...

When Selenium is not in headless mode, it cannot capture a screenshot of the entire website

Disclaimer: Although there is a similar question already out there, none of the answers provided worked for a headless browser. Therefore, I have decided to create a more detailed version addressing this specific issue (the original question I referred to ...

Python sends back a list containing garbled characters to Ajax

Need help fixing the output of a Python list returned to Ajax, as it appears strange. ap.py @app.route('/_get_comUpdate/', methods=['POST']) def _get_comUpdate(): comNr = request.form.get('comNr') com_result ...

What is the reason that dynamic languages do not have a requirement for interfaces?

In Python, do we not need the concept of interfaces (like in Java and C#) simply because of dynamic typing? ...

Combine video using ffmpeg (or similar tools) while incorporating additional elements (such as overlays)

I am currently in the process of scraping clips from Twitch and combining them into a single video file. I have successfully managed to scrape Twitch clip links, but I am only able to get 16-20 videos due to the need to scroll with Selenium. While this is ...

Alternating between minimum and maximum based on user input

I'm currently facing an issue with my code where the min filtering works on element 1, but the max filtering works on element 2. Does anyone have suggestions for a more efficient way to handle this? from operator import itemgetter data = [['A&ap ...

Python Code: Traversal algorithm for expanding tree structures at every node

I possess a dictionary containing IDs and several string values associated with each ID. When querying the database for each value corresponding to an ID, I receive a unique set of results: {111: Run, Jump, swim} {222: Eat, drink} For every value like "R ...

Replace all characters processed by unescape (beyond just &, <, and >) with HTML escape

Is html.escape() symmetrical to .unescape()? The docs state that escape only converts &, <, and >, whereas .unescape handles "all named and numeric character references". How can I escape all characters that .unescape() unescapes? Current behavior: ...

How come the `get_success_url` function always redirects me back to the original page in Django?

As a newcomer to Django, I've been working on a project for a few months and recently decided to restructure it to leverage Django's Models more effectively. The issue I'm facing is that when populating a form with a model-based view (Create ...

The py2exe package was not found in the system

I'm in the process of converting a Tkinter application into an executable file using py2exe. Everything seems to be working correctly, except when a specific function is called, the .exe file generates the following error: Exception in Tkinter callba ...

Unable to import submodules within a Python package

I am facing an issue with my Python package. It works fine when used standalone, but after installing it to site-packages using pip, I lose the ability to import submodules. Here is the structure of my package: mypackage mypackage __init__.py ...

What information can be gathered from the Python requests stack trace?

I am encountering an issue while attempting to make a request call to Elasticsearch. I can successfully execute the same call from a basic script. However, when I convert a list into a string and pass it to the payload, I receive the following stack trace: ...