简体   繁体   中英

Remember command line variables in python

I want to make the command line run in python.

For Example:

import subprocess

subprocess.call('set /A x = 5', shell=True)  
subprocess.call('echo %x%', shell=True)  

I'd like that i remember the value 5 that x was set to. But instead it echos just %x% as a string.

Using a subprocess means very concretely that you run another process. The process in which the variable was set will no longer exist when control returns from the subprocess back to Python.

Try

import os
import subprocess

env = os.environ.copy()
env['x'] = '5'
subprocess.check_call(
    'echo %x%',
    shell=True,
    env=env)

Notice also the switch to check_call - it probably doesn't matter a great deal here, but you should usually check for subprocess failures.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM