英文:
Run system command in same context of the script itself
问题
我有一个脚本,运行一组命令,其中一个命令需要在运行前设置一些环境变量。问题是,系统命令作为一个独立的进程启动,我在那里设置的任何环境变量对脚本运行的上下文不可见。我该怎么解决这个问题?
system("set WALLET=NO");
执行一些 Perl 命令; #这个命令需要设置环境变量 WALLET=NO
英文:
I have a script that runs a set of commands and it needs some env variable to be set before running one of the commands. The problem is that system command launches as a separate process, and any env variables that i set there, are not visible for the context that the script runs in. How can I overcome this?
system("set WALLET=NO");
do some perl commands; #this command needs env variable WALLET=NO to be set
答案1
得分: 7
环境变量可以使用 %ENV 哈希在程序中设置。
$ENV{WALLET} = 'NO';
运行需要使用 ENV 的 Perl 命令
这个程序中设置的变量在这个程序及其子程序中可见,而不在其父程序中。
程序如何“知道”是否需要设置它?这将由先前执行的 shell 操作以最适合你的方式进行通信。作为一个简单的例子,它们可以返回设置变量的指令。
my $set_var = qx("script_that_sets_var_and_returns_flag");
# 可能需要处理返回以获取标志值
if ($set_var) {
$ENV{WALLET} = 'NO';
...
}
在这里使用的“反引号”是以其操作符形式 qx 使用的,它们返回子shell中发生的一切的 stdout 流(与 system
不同)。有一些库在运行外部命令时更复杂(或简单)。
根据 shell 中实际发生的情况,可能需要处理返回以提取所需标志的值。
或者,在 shell 中执行的操作可以写一个类似配置文件的文件,可能只是具有 var=value 对的行,然后在 Perl 脚本中可以读取该文件。然后你需要一些协议,可能相当简单,用于表示有哪些标志及其含义。
有了更多细节,我们可以提供更精确的答案。
英文:
An environment variable can be set in the program using %ENV hash
$ENV{WALLET} = 'NO';
run_perl_command_that_needs_ENV()
The variable set in this program is seen in this program and its childrenm, not in its parent .
How does the program "know" whether it needs to set it? That would be communicated by the shell operations executed previously, in whatever way you find most suitable. As a simple example, they can return an instruction to set the variable
my $set_var = qx("script_that_sets_var_and_returns_flag");
# perhaps need to process the return for the flag value
if ($set_var) {
$ENV{WALLET} = 'NO';
...
}
The "backticks," used here in their operator form qx, return the stdout stream from whatever goes down in the subshell (as opposed to system
, which doesn't). There are libraries which are way, way more sophisticated (or simple) in running external commands.
Based on what actually happens in shell the return may need be processed to extract the value of the needed flag.
Or, operations done in the shell can write a configuration file of sorts, perhaps as simple as lines with var=value pairs, and then back in the Perl script that file can be read. Then you'd need some protocol, likely rather simple-minded, for what flags there are and what they mean.
With more detail perhaps we can provide more precise answers.
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论