Python self printing program

Print itself is a draft programming task. It is not yet considered ready to be promoted as a complete task, for reasons that should be found in its talk page.

Create a program, which prints its source code to the stdout!

11l [ edit ]

:start: -V sourceFileName = fs:path:split_ext(:argv[0])[0]‘.11l’ print(File(sourceFileName).read())

Ada [ edit ]

-- Print the program's source to standard output -- J. Carter 2023 Apr -- Apparently it's acceptable to open the source file and copy it to the output with Ada.Text_IO; procedure Autoprint is Source : Ada.Text_IO.File_Type; begin -- Autoprint Ada.Text_IO.Open (File => Source, Mode => Ada.Text_IO.In_File, Name => "autoprint.adb"); All_Lines : loop exit All_Lines when Ada.Text_IO.End_Of_File (Source); Ada.Text_IO.Put_Line (Item => Ada.Text_IO.Get_Line (Source) ); end loop All_Lines; Ada.Text_IO.Close (File => Source); end Autoprint; 

Batch File [ edit ]

@echo off for /f "tokens=*" %%s in (%~n0%~x0) do (echo %%s) 

Ecstasy [ edit ]

module test  @Inject Console console; void run()  console.print($./test.x); > > 

FreeBASIC [ edit ]

Furor [ edit ]

1 argv getfile dup sprint free end

Peri [ edit ]

###sysinclude standard.uh ###sysinclude args.uh ###sysinclude str.uh ###sysinclude io.uh 1 argv getfile dup sprint end

Go [ edit ]

package main import ( "fmt" "io/ioutil" "log" "os" "path" ) func main()  self := path.Base(os.Args[0]) + ".go" bytes, err := ioutil.ReadFile(self) if err != nil  log.Fatal(err) > fmt.Print(string(bytes)) > 

Just the invoking line as remainder is, of course, as above.

J [ edit ]

In J’s command line environment, many programs, including the empty program (is nothing, takes no arguments, produces nothing), print themselves to standard output. This is especially true when the language has been configured (with 9!:3(5) ) to present verbs using their linear representation (which is highly recommendable as part of the system profile for most J users). But numeric constants can be thought of as programs which take no arguments and have themselves as their result.

Though, of course, it’s also true that these programs can be assembled as components in larger programs.

prim=: 2 3 5 mean=: +/ % # mean prim 3.33333 

jq [ edit ]

Works with gojq, the Go implementation of jq

A jq program that contains any JSON entity formatted as though by jq will print itself. The shortest such program would be a single digit, e.g.:

Example invocation: jq -n 0

Julia [ edit ]

The running program’s filename is referenced as the builtin PROGRAM_FILE variable in Julia.

""" Read the program file and print it. """ printitself() = print(read(PROGRAM_FILE, String)) printitself() 

Ksh [ edit ]

#!/bin/ksh # Program to print it's own source code ###### # main # ###### while read line; do print "$line>" done < $0 

Lua [ edit ]

-- arg[0] contains the name of the invoked script. print(io.open(arg[0]):read"*a") 

Nanoquery [ edit ]

println new(Nanoquery.IO.File).open(args[1]).readAll()

Nim [ edit ]

We suppose that the source file is in the same directory as the executable file.

import os let execFile = getAppFilename() let sourceFile = execFile.addFileExt("nim") stdout.write sourceFile.readFile() 

Perl [ edit ]

# 20201011 added Perl programming solution use strict; use warnings; open my $in, ', $0 or die; print while ; close($in) # @ARGV=$0; print <> # slurp without an explicit open() 

Phix [ edit ]

puts(1,get_text(command_line()[2]))
puts(1,get_text(command_line()[2]))

Interpreted or compiled — latter only works while executable and source are still in the same directory, and not renamed.

puts(1,get_text(substitute(command_line()[2],".exe",".exw")))
>p test ;; or p -c test puts(1,get_text(substitute(command_line()[2],".exe",".exw")))

Alternative — see the docs (ie phix.chm) for an explanation of the («») and [1][2]:

?get_text(include_path("")&include_files()[1][2])
"?get_text(include_path("")&include_files()[1][2])"

PowerShell [ edit ]

Write-Host $MyInvocation.MyCommand 

Python [ edit ]

with open(__file__) as f: print(f.read()) 

Raku [ edit ]

Not really sure what the point of this task is.

Is it supposed to be a quine?

Or just a program that when executed echoes its source to STDOUT? (Here’s probably the simplest valid program that when executed, echoes its source to STDOUT. It is exceptionally short: zero bytes; and when executed echoes zero bytes to STDOUT.)

Or are we supposed to demonstrate how to locate the currently executing source code file and incidentally, print it.

Whatever. Any of these satisfy the rather vague specifications.

REXX [ edit ]

/*REXX program prints its own multi─line source to the standard output (stdout). */ do j=1 for sourceline() call lineout , sourceline(j) end /*j*/ /*stick a fork in it, we're all done. */ 

Ring [ edit ]

fileName = filename() fp = fopen(fileName,"r") ? read(filename()) fclose(fp)
fileName = filename() fp = fopen(fileName,"r") ? read(filename()) fclose(fp)

Ruby [ edit ]

Wren [ edit ]

import "os" for Process import "io" for File var args = Process.allArguments System.write(File.read(args[1])) 

Just the invoking line as remainder is, of course, as above.

Z80 Assembly [ edit ]

This program prints its bytecode as text to the Amstrad CPC terminal. The program is run by typing call &1000 to the screen.

WinAPE Z80 Assembler V1.0.13 000001 0000 (1001) org &1001 000003 1001 21 01 10 ld hl,&1001 000004 1004 1E FF ld e,&ff ;0 is the terminator so we can't use zero as an immediate directly 000005 1006 1C inc e ;we have to abuse 8-bit underflow to get it. 000006 1007 loop 000007 1007 7E ld a,(hl) 000008 1008 BB cp e 000009 1009 CA 2B 10 jp z,ProgramEnd 000011 100C CD 36 10 call UnpackNibbles 000012 100F 78 ld a,b 000013 1010 FE 0A cp &0A 000014 1012 38 02 jr c,noCorrectHex_B 000015 1014 C6 07 add &07 000016 1016 noCorrectHex_B 000017 1016 C6 30 add &30 000018 1018 CD 5A BB call &bb5a 000020 101B 79 ld a,c 000021 101C FE 0A cp &0A 000022 101E 38 02 jr c,noCorrectHex_C 000023 1020 C6 07 add &07 000024 1022 noCorrectHex_C 000025 1022 C6 30 add &30 000026 1024 CD 5A BB call &bb5a 000027 1027 23 inc hl 000028 1028 C3 07 10 jp loop 000029 102B ProgramEnd 000030 102B 3E 30 ld a,&30 000031 102D CD 5A BB call &bb5a 000032 1030 3E 30 ld a,&30 000033 1032 CD 5A BB call &bb5a 000034 1035 C9 ret ;return to basic 000037 1036 UnpackNibbles 000038 1036 ;splits a into its component nibbles, storing high nibble in B and low in C. 000039 1036 F5 push af 000040 1037 E6 0F and &0f 000041 1039 4F ld c,a 000042 103A F1 pop af 000043 103B E6 F0 and &f0 000044 103D 0F rrca 000045 103E 0F rrca 000046 103F 0F rrca 000047 1040 0F rrca 000048 1041 47 ld b,a 000049 1042 C9 ret 000051 1043 00 db 0 ;this must be the only instance of 00 in the bytecode for this to work.

Источник

Self Printing Programs in Python

Let’s talk about self printing programs (or, quines). A self printing program is, as is its name, self explanatory. Today I thought about how to implement a quine in Python, I whipped up a solution on my own and then posed the challenge to some people in the office. These are the results:

My Version

s = r"print 's = r\" \"'.format(s), '\n', s" print 's = r\" \"'.format(s), '\n', s

This exemplifies a common way to implement a quine — the main problem is that you have to use some sort of function that prints. But of course, you also have to print that function, and so on. The way to deal with this is put the entire program in a string, except the assignment to that string, then print the assignment (where you can use the string itself to avoid explicitly writing it again, thus avoiding the recursion), and then the string. Notice there’s a lot of playing with quotation marks. Next is a version that tries to solve this.

Using chr for Quotation Marks

a = "b = chr(97) + chr(32) + chr(61) + chr(32) + chr(34); b += a; print b + chr(34); print a" b = chr(97) + chr(32) + chr(61) + chr(32) + chr(34); b += a; print b + chr(34); print a

This version (while a bit cumbersome) solves the quotation marks problem by just explicitly printing the ascii characters.

Using exec Instead of Repeating the print

s = r"print 's = r\"' + s + '\"' + '\nexec(s)'" exec(s)

I really likes this version, as it mostly avoids repeating the code in the two lines.

The Smartass Approach

Well, the first person I introduced this challenge to, had a pretty wiseass, but overall, clever approach. He did this:

This works, and is pretty clever, but it obviously isn’t what quines are all about. It also wouldn’t work in an interactive shell.

The “Google” Way

After I got the above answers, I just had to google Python quines and see what comes up. A StackOverflow thread points out this (pretty cool) snippet:

It assigns to the variable _ a string which is contains the entire code, except for its own value which is replaced by a formatting instruction, and then print _ and feeds itself into its formatting. Looks obfuscated, but it’s pretty cool when you take a deeper look.

Similar Posts

Источник

Self printing signature programs

Signature programs are short programs that people have been using as part of their signature. They are small (2 to 4 lines) programs, that are often rather cryptic because they have to save space as much as possible. On this page some self printing signature programs are presented. Self printing programs are also called Quines.

Below are three self printing programs in C written by Dario Dariol, which are described in the standard GNU distribution since 1990:

main(a,b)";b='"';printf(a,b,a,b,b);> main(a)";printf(a,34,a,34);> main(a)",34,a,34);>

Only the first version is ASCII independent. The first two are compiler independent. Dario also wrote a hiding siganture programs and a self-printing one in Java.

t c=c++show c;self=s"t c=c++show c;self=s"
main() %c" ,a,10,a,p,a,10,a," *** Email: xxxxxxx@xxx.xx *** IRC: Zuikkis *** ",a,10);>

A self printing Perl signature program by Dimator Shahbaz

import java.text.*;class a;char c[]=;String s[]=new String[3];s[0]="import java.text.*;class apublic static void main(String x[])char b[]=34>;char c[]=123>;String s[]=new String[3];s[0]=;s[1]=new String(b);s[2]=new String(c);System.out.println(MessageFormat.format(s[0],s));>>";s[1]=new String(b);s[2]=new String(c);System.out.println(MessageFormat.format(s[0],s));>>

Self printing Python signature program by BReflection

python -c "x='python -c %sx=%s; print x%%(chr(34),repr(x),chr(34))%s'; print x%(chr(34),repr(x),chr(34))"

Источник

Читайте также:  Java spring util map
Оцените статью