2013-04-30 52 views
3

This thread討論了從Bash腳本內運行Python代碼的方法。在Perl腳本上使用另一個解釋器運行代碼

有什麼辦法可以在Perl腳本中做類似的事情嗎?即有什麼辦法可以運行在Perl腳本上鍵入的Python代碼?請注意,我並不是要求從Perl腳本運行Python 文件。我詢問的是如何在具有Perl腳本的同一文件中直接鍵入運行Python代碼(與其他線程討論如何運行Bash腳本的Perl代碼的方式相同)。

例子:

# /bin/perl 
use 5.010 
my $some_perl_variable = 'hello'; 


# ... BEGIN PYTHON BLOCK ... 
# We are still in the same file. But we are now running Python code 
import sys; 
print some_perl_variable # Notice that this is a perl variable 
for r in range(3): 
    print r 
# ... END PYTHON BLOCK ... 

say "We are done with the Perl script!" 
say "The output of the Python block is:" 
print $output" 
1; 

應打印:

We are done with the Perl script! 
The output of the Python block is: 
hello 
1 
2 
3 

我們正在與perl腳本

+1

是的,同樣的技術(heredocs)適用。另請參閱所謂「單線」的「-e」和「-E」選項。 – amon 2013-04-30 23:09:34

+0

如果你描述你想要做什麼,這將有所幫助。你想從Perl腳本中運行Python代碼嗎?這是我寫的最好的猜測。 – Borodin 2013-04-30 23:26:39

+0

@Borodin我更新了OP。讓我知道如果這仍然不清楚。 – 2013-04-30 23:43:42

回答

4

這聽起來像你會對Inline模塊感興趣。它允許Perl以許多其他語言調用代碼,並依賴於每種語言的支持模塊。

你不說你想做什麼,但是你提到Python並且有一個Inline::Python

+0

啊,但Inline :: Python可以運行「生活在文件上」的python代碼,這是OP所害怕的。當然,它也可以(也更常見)運行生存在一個字符串中和/或直接在perl腳本中內聯的python代碼(因此名稱) - 但即使在這些情況下,perl腳本通常也存在於一個文件中,所以除非Python是動態生成的...即使如此,內存基本上是一個文件(字面上如此,在Linux上)。我認爲唯一的解決方案是確保python代碼永遠不會存在。 :) – abarnert 2013-04-30 23:40:04

+0

或者,更嚴重的是,是的,這似乎是你猜對的50/50的機率,即使你沒有,絕對是+1也可能是一個有用的答案。 – abarnert 2013-04-30 23:40:33

+0

@abarnert我更新了OP。我希望現在這個問題更清楚。對不起,我的問題一開始就令人困惑。 – 2013-04-30 23:53:10

2

是,相同的技術完成(這裏-文檔)可用於Perl的。

的Perl在擊:

perl <<'END' # note single quotes to avoid $variable interpolation 
use 5.010; 
say "hello world"; 
END 

perl -E'say "hello from perl"' 

擊在Perl:

use autodie; # less error handling 
open my $bash, "|-", "bash"; 
print $bash <<'END'; # single quotes again 
echo hello from bash 
END 

的Perl在擊在Perl:

use autodie; # less error handling 
open my $bash, "|-", "bash"; 
print $bash <<'END'; # single quotes again 
perl <<'INNER_END' 
use 5.010; 
say "hello inception"; 
INNER_END 
END 

(我在命令行上諷刺地測試過,在另一個heredoc中)

+0

您可能是對的:他只是想將Perl代碼放入Bash腳本中。在這種情況下,問題應該有不同的標籤: -//我們不知道,直到他停止對此事的沉默 – Borodin 2013-04-30 23:31:10

+0

偉大的。謝謝阿蒙和@Borodin。關於在Python和Perl之間共享變量的問題(請參閱我的更新後的OP) – 2013-04-30 23:50:33

+0

@ user815423426:第二次後續處理屬於Borodin的答案,而不是這一個。 – abarnert 2013-05-01 00:14:10