I'm working on Windows 7 and I have installed Strawberry. I would like to run a perl skript (test.pl):
open OUTPUT, ">test.txt";
print OUTPUT "This is a test\n";
by just clicking on the file or redirect with left mouse click to Perl-program (open with/perl.exe). When I do this a console opens for less than a second and disappears but the file test.txt is not created. If I go to the MS command and enter
> C:\myplace>perl test.pl
it works. I never had this experience before (WinXP, other Windows 7 PC with ActivePerl and Windows 8 with strawberry). I would be very happy if somebody could give me a hint how to solve this problem.
There are two problems here:
Creating the file where you want it. When double-clicking a perl script to launch it, it is not executed in the context of the folder you have opened in Explorer. If you want to specify an explicit context, do the following near the top of your script:
use FindBin; # This is a module that finds the location of your script
BEGIN { chdir $FindBin::Bin } # set context to that directory.
When you then create a new file without an aboslute path, the path is considered relative to that directory.
You do not have the problem when running the script from the command line, because you have specified the correct path. But if you run it from C:\ like
C:\> perl myplace/test.pl
then you have created the file in C\test.txt. The FindBin solution fixes this.
When running a script by double-clicking it, the command line exits before you can inspect the output. This “problem” is shared by all programming languages on Windows. You can force the window to stay open by waiting for some input. You can either do
system("PAUSE"); # not portable to non-Windows!
or
warn "Press enter to exit...\n";
<STDIN>; # Read a line from the command line and discard it.
# Feels akward when launching from the command line
to wait until an Enter ⏎ is pressed .
The other solution is to always use the command line for your scripts, which is what I'd actually suggest.
Check what is your script executing folder, as it might differ from C:\myplace
use Cwd;
print getcwd();
sleep 7;
Related
I am trying to run a Perl script from command prompt.
The script contains one line:
print "Hello World!\n"
I type in the cmd: Perl hello.pl
The line is printed in a new window and quickly is closed.
It's all happening in the cmd! Does anyone had this kind of problem?
I know Perl is working because I tried to run a script that creates an excel file and it worked.
The only problem is, that it doesn't print in the same window as it is supposed to do, but opens a new window, prints there and closes it. (I tried to do a while loop in the end and it didn't help).
I was able to solve this.
In windows there is an option called "Open command prompt as Administrator". A new window does not open up in that case.
The cmd window closes as soon as the command that it runs has exited. You can either
… start a cmd.exe of your own, and launch your script via
> perl C:\path\to\script.pl
instead of double-clicking the perl file (or whatever you are doing to start it). This should not start a new window.
… or you could have the script wait until you have read the message. Just wait for user input of some sort before exiting, e.g. like
<>; # read and discard a line to exit
at the bottom of your script.
You can also use the pause program for this, which you can execute like system('pause').
I want my Perl scripts to behave just like any other executable (*.exe file).
When I double-click on myscript.pl I want it to execute instead of opening in a text editor.
I want to run myscript.pl instead of perl myscript.pl.
I really want to run myscript instead of myscript.pl.
I want to run program | myscript instead of program | perl myscript.pl.
I want to be able to run my script via drag & drop.
There are a number of changes you have to make on Windows to make all of
these things work. Users typically stumble upon things that don't work one at
a time; leaving them confused whether they've made an error, there's a bug in
Perl, there's a bug in Windows, or the behavior they want just isn't possible.
This question is intended to provide a single point of reference for making
everything work up front; ideally before these problems even occur.
Related questions:
How do I make Perl scripts recognize parameters in the Win32 cmd console?
Running a perl script on windows without extension
Perl execution from command line question
How can I read piped input in Perl on Windows?
Perl on Windows, file associations and I/O redirection
How do I create drag-and-drop Strawberry Perl programs?
Note: The actions below require administrative privileges. For
steps utilizing the command prompt it must be launched via "Run as
administrator" on Windows Vista / Windows 7.
Associate *.pl files with perl
Run the following commands at a shell prompt:
assoc .pl=PerlScript
ftype PerlScript=C:\bin\perl.exe "%1" %*
Replace C:\Perl\bin\perl.exe with the path to your Perl installation. This
enables you to run myscript.pl instead of perl myscript.pl.
Default install locations are:
ActivePerl: C:\Perl
Strawberry Perl: C:\Strawberry
Add .PL to your PATHEXT environment variable.
This makes Windows consider *.pl files to be executable when searching your
PATH. It enables you to run myscript instead of myscript.pl.
You can set it for the current cmd session
set PATHEXT=%PATHEXT%;.PL
To set it permanently (under Windows Vista or Windows 7)
setx PATHEXT %PATHEXT%;.PL
Under Windows XP you have to use the GUI:
Right-click My Computer, and then click Properties.
Click the Advanced tab.
Click Environment variables.
Select PATHEXT, then click Edit.
Append ;.PL to the current value.
Make I/O redirection work
I/O redirection (e.g. program | myscript) doesn't work for programs started
via a file association. There is a registry patch to correct the problem.
Start Registry Editor.
Locate and then click the following key in the registry:
HKEY_LOCAL_MACHINE\Software\Microsoft\Windows\CurrentVersion\Policies\Explorer
On the Edit menu, click Add Value, and then add the following registry value:
Value name: InheritConsoleHandles
Data type: REG_DWORD
Radix: Decimal
Value data: 1
Quit Registry Editor.
Warning: In principle, this should only be necessary on Windows XP. In my experience it's also necessary in Windows 7. In Windows 10 this is actively harmful—programs execute but produce nothing on stdout/stderr. The registry key needs to be set to 0 instead of 1.
See also:
STDIN/STDOUT Redirection May Not Work If Started from a File Association
Perl Scripts on Windows 10 run from Explorer but not Command Prompt
If patching the registry isn't an option running program | perl -S myscript.pl
is a less annoying work-around for scripts in your PATH.
Add a drop handler
Adding a drop handler for Perl allows you to run a Perl script via drag & drop;
e.g. dragging a file over the file icon in Windows Explorer and dropping it
there. Run the following script to add the necessary entries to the registry:
use Win32::TieRegistry;
$Registry->Delimiter("/");
$perlKey = $Registry-> {"HKEY_CLASSES_ROOT/Perl/"};
$perlKey-> {"shellex/"} = {
"DropHandler/" => {
"/" => "{86C86720-42A0-1069-A2E8-08002B30309D}"
}};
Convert your perl scripts into batch files using pl2bat once they are ready to be run by users.
The trick works through the perl -x switch which, according to perldoc perlrun, makes Perl search for the first line looking like #!.*perl.
After following the instructions in the accepted answer, a double click still led to .pl files opening with Notepad in Windows 10 — even when perl.exe was set as the default file handler.
After finding Jack Wu's comment at ActivePerl. .pl files no longer execute but open in Notepad instead I was able to run perl scripts on double-click as such:
Select and right-click a .pl file
Use the "Open With" submenu to "Choose another app"
Select "Always use this app to open .pl files" (do this now – you won't get the chance after you have selected a program)
Scroll to the bottom of the "Other options" to find "More apps", and select "Look for another app on this PC"
Navigate to C:/path/to/perl/bin/ and select Perl5.16.3.exe (or the equivalent, depending on which version of Perl you have installed: but not Perl.exe)
Then the Perl icon appears next to .pl files and a double-click leads to them opening in Perl every time, as desired.
I tried the assoc and ftype methods and they didn't work for me.
What worked was editing this registry key:
Computer\HKEY_CURRENT_USER\Software\Classes\Applications\perl.exe\shell\open\command
It was set to:
"C:\Perl64\bin\perl.exe" "%1"
When it should be:
"C:\Perl64\bin\perl.exe" "%1" %*
It is the same content as the ftype, but for arcane windows reasons, I had to set it there too.
Like some others, I had set 'assoc' and 'ftype', but also had set Notepad text editor via the GUI, and when I tried to execute a script via the command line, Windows invoked Notepad to edit the script instead of running my script.
Using the GUI to instead point the .pl file association to the script-running executable was not much of an improvement, since it would invoke the executable on my script, but would pass no command-line arguments (even when I invoked my script from the command line).
I finally found salvation here which advised me to delete some registry keys.
Key quote:
"The problem is that if you have already associated the program with the extension via the Open With dialog then you will have created an application association, instead of a file extension association, between the two. And application associations take precedence."
In my case, following the instructions to use RegEdit to delete
HKEY_CLASSES_ROOT \ Applications \ perl.exe
where perl.exe is the name of my Perl executable, and then also deleting:
HKEY_CLASSES_ROOT \ .pl
seemed to solve my problem, and then (after re-executing 'assoc' and 'ftype' commands as shown in other answers) I could then execute scripts from cmd.exe and have them run with access to their command-line parameters.
Some other related information here.
I am trying to write my first test case in perl with the help of Test::Simple module.
I have saved the file with .t extension now when i am trying to run this file on windows system then it says windows can not open this file.
I had googled about this and what i found is for running this file you should make a new directory with name /t and keep this file to there.
http://perlmeme.org/tutorials/writing_test_harness.html
I have tried this also but still it is not working.
Can any body gives me some tips.
following is my Test cases :
#!/usr/bin/perl -w
use Test::Simple tests => 2;
ok( 1 + 1 == 2 );
ok( 2 + 2 == 5 );
A .t file in Perl is just a Perl script. The .t is just there to let you know that it's a test script instead of something else. The file extension and directory structure really doesn't matter, it's there just to help you can keep your environment clean.
To run a Perl script on Windows, from a command line, simply type perl <script name>. Make sure that you have a Perl executable installed on your system as Windows does not come with one by default, and make sure it is in your path. If the script you want to run is not in your current directory, make sure to specify the path to the script.
In the URL you gave it says:
Now because 'dot-T' files are just normal Perl scripts, you can run them as such -
perl t/Monger.t
Is it a typo in your post, you wrote /t as a directory to keep your test files in - it should be t/, so just a directory relative to where you are. (That's "just" a convention.)
Using tortoiseSVN client side hook script for pre-commit, we are trying to run some unit test cases using Test::Harness's runtests sub.
In TortoiseSVN's Setting->Hook Scripts->Configure Hook Scripts (for pre-commit), I provide a batch file name against the "Command Line to Execute:" heading.
This batch file contains, the following line
run.pl unittest.t
run.pl contents
#!/usr/bin/perl -w
use strict;
use warnings;
use Test::Harness;
# Run a single test suite
my #files = #ARGV;
runtests(#files);
So, when I try to commit any code, this script get invoked and failed with the following error message:
Could not execute (D:\Perl589\bin\perl.exe -w D:\t\unittest.t): open3: Can't call method "close" on an undefined value at D:/Perl589/lib/IPC/Open3.pm line 368.
Any idea how can we resolve this issue.
Does your Windows computer know what to do with scripts that ends in *.pl? That is, if you double click on a .pl file, does it run Perl? This is set in the registry. You set this up under the File Types tab in the Folder Options. In older version of Windows, this could be done via the Tools->Folder Options... menu. I'm not sure where this can be done in Vista and Windows 7.
Once you have the relationship between Perl and the *.pl files setup, you also have to edit your %PATHEXT% environment variable to include .PL in the list of suffixes that are considered executables.
Otherwise, you simply have to put the name of the Perl interpreter in your Batch file's hook script:
C:\Perl\bin\perl run.pl unittest.t
One more possibility is to use the pl2bat script that came with your Perl installation that turns Perl scripts into Batch files.
I have a executable that when double clicked opens in a command line window.
Now there is a input file (i.e named "sphere_15000.inp") in the same directory where the executable apame_win64.exe is located. So we can inter the file name in the command line.
The question is how this can be done from mathematica front end? With the RunThrough command I tried to do it with no avail.
RunThrough["Executable Location", "sphere_15000"]
Do I need to put this file location in my Windows 7 environment path variable? Hope for some suggestion in this regard.
UPDATE
Found a solution to my problem.
First set the Mathematica directory to the folder where the executable is located.
path="C:\Users\FlowCrusher\Desktop\CUSP solver\Apame_build_2011_01_09\solver";
SetDirectory[path];
Then use the following style of input.
Run["\"\"apame_win64.exe\" \"input\"\""]
Here "apame_win64.exe" is the executable one want to run and "input" is the input file for the executable. This solves the problem. But a new item in the wishlist.
Is there a way to hide the console window in the background?
Here is how it looks on my screen.
As Chris suggested if we use minimized console in the Run command we get a minimized window but the program does not execute.
I hope that a solution exists.
BR
Yes, you might put the folder of you executable into the Path variable, or provide the full path name.
However, RunThrough seems to have been superseeded (on Windows) by
Import["!command ","Text"], which will execute command and read the comaand line output into Matheamtica as a string.
E.g.:
Export["testit.txt", "bla", "Text"];
Import["!dir" <> " testit* > dir.log", "Text"];
FilePrint["dir.log"]
--
Otherwise, I also had good results in the past using NETLink (not sure if WScript.shell
still works on Windows7/8 or if one should use something else).
Emulating Run (RunThrough is not really needed I think):
Run2[cmd_String] := Module[{shell},
Switch[$OperatingSystem,
"Windows",
Needs["NETLink`"];
shell = NETLink`CreateCOMObject["WScript.shell"];
shell # run[cmd,0,True],
"Unix",
Run # cmd,
"MacOSX",
Run # cmd ] ];
Can you run your application with input from a basic command window instead of the application console? This might be the form of command you would need:
apame_win64 -input sphere_15000.inp
or simply
apame_win64 sphere_15000.inp
You can probably check the available switches by running apame_win64 -help
A multi-part command can be run from Mathematica, e.g.
Run["type c:\\temp\\test.txt"]
Alternatively, also returning output to the Mathematica session:
ReadList["!type c:\\temp\\test.txt", String]
I landed here wanting to run abaqus command line on windows.
The solutions provided here worked out for me (Windows 7, Mathematica 9):
SetDirectory#path;
Run["start /min abaqus job=" <> fileName <> " interactive ask_delete=OFF >> log.txt"]
(Here the abaqus option ask_delete=OFF overwrites an existing simulation results and the >> redirects all the output to a file)
I think, minimizing the window did not run in your case since the executable throws open that window. In that case, this might be of some help