Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Code playground do not allows users input via "input()" #82

Open
lopezbec opened this issue Apr 11, 2024 · 0 comments
Open

Code playground do not allows users input via "input()" #82

lopezbec opened this issue Apr 11, 2024 · 0 comments

Comments

@lopezbec
Copy link
Owner

The code for the code playground is running whatever is typed into the console as a subprocess. That is, it saves everything typed as a script and then is run and it output shown later (see lines 73-77 here: https://github.com/lopezbec/AI_Gamification_Python/blob/main/command_line_UI.py)

One potential solution is to use 'subprocess.Popen". Based on ChatGPT here is a potential solution that would need to be modified to fit out needs:

'The subprocess.run() function executes the specified command in a subprocess. If you want to simulate user input using input() within the subprocess, you can't directly achieve it with subprocess.run().

subprocess.run() doesn't interact with the standard input/output streams of the subprocess once it's launched. Instead, you might consider using subprocess.Popen() which allows you to communicate with the subprocess's standard streams.

Here's an example of how you might achieve this:'

`import subprocess

#Launch the subprocess
proc = subprocess.Popen([sys.executable, script_filename],
stdin=subprocess.PIPE,
stdout=subprocess.PIPE,
stderr=subprocess.STDOUT)

#Send input to the subprocess
user_input = b"your_input_here\n" # Add '\n' to simulate hitting Enter after input
proc.stdin.write(user_input)
proc.stdin.flush() # Ensure input is sent

#Read output from the subprocess
output = proc.stdout.read()

#Wait for the subprocess to finish
proc.wait()

#Close the subprocess's stdin to signal that no more input will be sent
proc.stdin.close()

#Decode the output from bytes to string
output_str = output.decode('utf-8')

print(output_str)
`
This script will launch the subprocess, send input to it, read its output, and then wait for it to finish. You can adjust this to fit your specific use case. Remember to handle errors and exceptions appropriately.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

1 participant