Reputation: 51
Today, I write a bash script to open and close a special python virtual envionment. You want to close the virtual environment, you must in the same bash process with command deactivate, so you can use command ~source~ to execute you bash script.(Preface)
Here is my perl script
#!/usr/bin/perl
BEGIN{
$\="";
}
use warnings;
use strict;
use feature "switch";
use Cwd qw(chdir cwd);
no warnings "experimental::smartmatch";
our $path = $ENV{"PATH"};
if($path =~ /sspider\/bin/){
print "Scrapy virtual environment opened already\n";
print "Do you want to close it? [y/n]:";
chomp(my $answer = <STDIN>);
given($answer){
when(/[yY\n]/){
my @path = split(/:/, $path);
my $scrapy_path;
for (@path){
if(/sspider/){
$scrapy_path = $_;
}
};
print $ENV{PWD}, "\n";
chdir("$scrapy_path") or die "Can't goto scrapy bin directory";
print $ENV{PWD}, "\n";
system("deactivate");
print "Closed successfully\n";
}
}
}
Because when I execute the perl script, it is running in a new process, so it can't close the virtual environment.
So, I want to know how to solve it.(Execute a command in the current bash process in perl script.
Upvotes: 1
Views: 462
Reputation: 123639
It is impossible to run Perl code as part of the current bash process. Bash cannot execute Perl code by its own so it needs to run the Perl interpreter - which is separate program and thus will run as a new process.
What might be done though is to create some file by the Perl program which then gets sourced by the shell - thus running the shell-instructions in this created file in the context of the current shell.
Upvotes: 1