简体   繁体   English

Python subprocess.call问题

[英]Python subprocess.call issue

When I run the following in Python 3.2.3 in Linux it does nothing... 当我在Linux中的Python 3.2.3中运行以下命令时,它什么也没做...

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. 我之前没有使用subprocess.call的问题。 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. 我以超级用户身份运行,所以这不是sudo的事情,并且我还尝试将r放在字符串前面以使其成为原始字符串。

Any ideas? 有任何想法吗? Thanks. 谢谢。

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. 当您通过子进程运行它时,将创建一个新的shell,修改环境,然后立即销毁它。

When you run it in a shell, it modifies the environment of that shell so you can see the effect. 在外壳中运行它时,它会修改该外壳的环境,以便您可以看到效果。

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): 要在Python中(在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: 如果要为单个命令修改环境,则可以传递env参数:

#!/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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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