简体   繁体   English

Python子进程为变量赋值

[英]Python subprocess assign value to a variable

I am using the following code:我正在使用以下代码:

import subprocess
#subprocess.call(["cat","contents.txt"])
command = "VAR=$(cat contents.txt | grep token)"
subprocess.call(command, shell = True)
subprocess.call(["echo","$VAR"])

I am trying to assign value of token present in contents.txt to a variable and i am trying to print the variable.我正在尝试将 contents.txt 中存在的令牌值分配给一个变量,并且我正在尝试打印该变量。 But i am not getting anything.但我没有得到任何东西。 What corrections can be done here.这里可以做哪些修正。

Thanks谢谢

You got to do everything in one process, since os.environ is for the particular python process and subprocess executes your commands in another process, you can't access it from there.您必须在一个进程中完成所有操作,因为os.environ用于特定的 python 进程,而subprocess进程在另一个进程中执行您的命令,因此您无法从那里访问它。

you also can't do it in two different subprocess.call calls since each is another process and you could not access the variable from the second one, therefore you have to execute everything in the same process, all commands at the same line, separated by ";", as follows:您也不能在两个不同的subprocess.call调用中执行此操作,因为每个调用都是另一个进程,您无法从第二个进程访问变量,因此您必须在同一进程中执行所有内容,所有命令都在同一行,分开用“;”,如下:

import subprocess
result = subprocess.run('VAR=$(cat contents.txt | grep token); echo $VAR', shell=True, stdout=subprocess.PIPE, stderr=subprocess.STDOUT)
print(result.stdout.decode())

in my contents.txt file I have "token=123", and hence the result of result.stdout.decode() was "token=123" as well :D在我的contents.txt文件中,我有“token=123”,因此result.stdout.decode()的结果也是“token=123”:D

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

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