简体   繁体   中英

How to write a program that outputs the source code?

You are asked to write a program that prints the source-code of the above program as its output.

To test your program, you can proceed as follows:

  1. Run your program and save the generated output to a file named generated.py
  2. Run generated.py and examine its output.

We assume that your initial Python program is in file lab3_x.py the following steps must be run in the PyCharm terminal:

 %python lab3_x.py > generated.py %python generated.py

Notice the output redirection > . It causes the output of program lab3_x.py to be written to the file generated.py . The output of lab3_x.py is the python program (source code) that converts stuff. (You may open file generated.py with Pycharm and check its contents!)

My questions are as follows:

  1. What does > do when written in the terminal?
  2. Does it has to open a fully working program when generated.py is executed in terminal?
  3. When I try to lab3_x.py > generated.py it opens up a new file named after generated.py , but with nothing inside. Why is this?

My code:

print('# Fahrenheit to Celsius conversion program\n')
print("fahren = float(input('Enter degrees Fahrenheit: '))")
print("celsius = (fahren - 32) * 5 / 9")
print("print(fahren, 'degrees Fahrenheit equals',")
print("      format(celsius.'.1f'), 'degrees Celsius')")

When you run your code, you are using redirection ">" which outputs the code to a file. So your print statements actually print to the python file, which should be executable assuming the print statements result in a correct python file.

So lab3_x.py > generated.py will write the print statements onto the python file/

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM