0

When I run the following in Python 3.2.3 in Linux it does nothing...

subprocess.call("export TZ=Australia/Adelaide", shell=True)

However if I run it in the terminal it works...

export TZ=Australia/Adelaide

I haven't had an issue with using subprocess.call before. Just seems to be this one. I'm running as a superuser so it's not a sudo thing, and I've also tried putting an r in front of the string to make it a raw string.

Any ideas? Thanks.

asked Sep 24, 2015 at 5:11
4
  • 2
    If you want to modify environment variables within Python read up on os.environ. Commented Sep 24, 2015 at 5:18
  • @metatoaster I've got this but it is still only a local scope within the program. When I exit the program it remains as it was. Is there a way to make the OS update permanently? os.environ['TZ'] = 'Australia/Adelaide' time.tzset() Commented Sep 24, 2015 at 6:32
  • 1
    You need to invoke OS/shell specific method of modifying this, such as modifying .bashrc, /etc/environment, or /etc/timezone if your Linux distribution supports that. Commented Sep 24, 2015 at 6:42
  • related: Calling the "source" command from subprocess.Popen Commented Sep 24, 2015 at 19:37

2 Answers 2

3

Export modifies the environment of the shell.

When you run it through subprocess, a new shell is created, the environment modified and then immediately destroyed.

When you run it in a shell, it modifies the environment of that shell so you can see the effect.

answered Sep 24, 2015 at 5:15
Sign up to request clarification or add additional context in comments.

Comments

1

A subprocess (shell in this case) can't (normally) modify its parent environment.

To set the local timezone for the script and its children in Python (on Unix):

#!/usr/bin/env python3
import os
import time
from datetime import datetime, timezone
os.environ['TZ'] = 'Australia/Adelaide'
time.tzset()
print(datetime.now(timezone.utc).astimezone())
# -> 2015年09月25日 05:02:52.784404+09:30

If you want to modify the environment for a single command then you could pass env parameter:

#!/usr/bin/env python
import os
import subprocess
subprocess.check_call('date', env=dict(os.environ, TZ='Australia/Adelaide'))
# -> Fri Sep 25 05:02:34 ACST 2015
answered Sep 24, 2015 at 19:32

Comments

Your Answer

Draft saved
Draft discarded

Sign up or log in

Sign up using Google
Sign up using Email and Password

Post as a guest

Required, but never shown

Post as a guest

Required, but never shown

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.