0

I have this code:

import os

os.system('set x=5')
os.system('echo %x%')

When I do this, I expect to get 5 outputted to the screen, but instead I get %x%. I think this is because these two commands are being run on 2 different command prompt instances. If anyone can help, that would be greatly appreciated!

2
  • os.system('set x=5 && echo %x%')? Commented Sep 18, 2019 at 0:33
  • But assuming I want to do it from 2 separate commands, what would I do? Commented Sep 18, 2019 at 0:35

2 Answers 2

1

It seems "set" command should be replace with "os.environ" method in python. This way, you can set environment variable.

import os
os.environ['x'] = "5"
os.system('echo %x%')

#result is "5"

I think this is the easiest way to achieve your goal. Hope this can help you:)

Sign up to request clarification or add additional context in comments.

2 Comments

Thank you for your reply, but as I said above, I would like to do it from 2 separate commands. The example I have given is a simplified version of what I hope to do.
@Pokechu48 thank you for your quick feedback. I changed my reply. I think you should use "os.environ" instead of using "set" command in "os.system" method.
0

It's not exactly recommended to do this but if you really want to programmatically interface with a console emulating the way you would do it normally you can manipulate the stdin and stdout buffers. The subprocess module has some tools for that in python.

import subprocess

p = subprocess.Popen('cmd.exe', stdin=subprocess.PIPE, stdout=subprocess.PIPE, universal_newlines=True)
p.stdin.write('set x=5\n')
p.stdin.write('echo %x%\n')
print p.communicate()[0]
p.terminate()

Comments

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.