0

I have a requirement to run python commands at run on shell programmatically, its almost replicating REPL but programmatically, I tried below code which worked for the first line but it's not carrying the session the way CLI does, kindly help

enter image description here

import subprocess as s
import sys
res=s.run([sys.executable, "-c", "a=5"])
s.run([sys.executable, "-c", "print(a)"])

Error:

Traceback (most recent call last):
  File "<string>", line 1, in <module>
NameError: name 'a' is not defined

I am getting the error as those 2 commands are being executed in 2 different processes, is there any way to run in one process but in different lines(Similar to what we do in python interpreter(REPL)), I am working on the requirement to capture python commands from some external files and run them on the shell, so I won't know what command I will be executed until it actually appears in an external file.

[![enter image description here][2]][2]

4
  • 1
    What do you think the error message is trying to tell you? Commented Jan 9, 2021 at 13:05
  • 2
    Variables aren't going to persist across two separate executions of the Python interpreter. That a=5 from the first execution isn't relevant to the second, which is why you're getting that NameError. I'm not entirely clear what you're trying to do so I don't have any particular suggestions for you. Commented Jan 9, 2021 at 13:06
  • @larsks thanks for the reply, is there any way to run in one execution but in different lines(Similar to what we do in python interpreter(REPL)), I am working on the requirement to capture python commands from some external files and run them on the shell, so I won't know what command I will be executing until its actually appeared in an external file. Commented Jan 9, 2021 at 13:12
  • My best advice for you right now is to update the question to demonstrate clearly what you're trying to accomplish. People aren't necessarily going to see your comment, and even with that comment I'm not entirely sure what you're trying to do. Commented Jan 9, 2021 at 13:15

1 Answer 1

1

You can use Popen of subprocess. stdin is waiting your commands.

import subprocess as s
import sys
res=s.Popen(sys.executable, stdin=s.PIPE)
res.stdin.write(b"a=5\n")
res.stdin.write(b"print(a)")
Sign up to request clarification or add additional context in comments.

5 Comments

thanks for the response, but it's not printing any value. Kindly help
@NewDev I have tested it is printing to output. How do you run the file?
i ran it from pyCharm, i have attached screenshot to question, kindly take a look at it
Please run it on the command line. python test_Selenium.py
Awesome, Thanks for the help

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.