Home > Enterprise >  How to run Python file in another python file?
How to run Python file in another python file?

Time:12-08

I'm trying to run another python file within this lexical analyzer, but it's not working. Can anyone help me?

I'm using this code: https://github.com/huzaifamaw/Lexical_Analyzer-Parser_Implemented-in-Python/blob/master/main.py

It says I can input my own files by changing blankvar, this is what I wrote:

filecheck = print("INPUT FILE:\n", hello.py)

to run a file called hello.py - to count the lexemes within it.

Can anyone help me? It'll be much appreciated :)

CodePudding user response:

You cannot use hello.py in:

filecheck = print("INPUT FILE:\n", hello.py)

If you want to modify the existing program, you have various options. The easiest is setting blank_var in this line to your program text.

This is what I did and got the following output:

blank_var = "import json\n\ndef foo(): pass\n\ndef bar(n):\n    print(n)\n"

Give this output (not sure about the ERROR IN START message)

INPUT FILE:
 import json

def foo(): pass

def bar(n):
    print(n)

{'value': 'import', 'LINE_NUMBERS': 1, 'TYPE': 'IDENTIFIER'}
{'value': 'json', 'LINE_NUMBERS': 1, 'TYPE': 'IDENTIFIER'}
{'value': 'def', 'LINE_NUMBERS': 3, 'TYPE': 'IDENTIFIER'}
{'value': 'foo', 'LINE_NUMBERS': 3, 'TYPE': 'IDENTIFIER'}
{'value': '(', 'LINE_NUMBERS': 3, 'TYPE': 'LL_BRACKET'}
{'value': ')', 'LINE_NUMBERS': 3, 'TYPE': 'RL_BRACKET'}
{'value': ':', 'LINE_NUMBERS': 3, 'TYPE': 'COLON'}
{'value': 'pass', 'LINE_NUMBERS': 3, 'TYPE': 'IDENTIFIER'}
{'value': 'def', 'LINE_NUMBERS': 5, 'TYPE': 'IDENTIFIER'}
{'value': 'bar', 'LINE_NUMBERS': 5, 'TYPE': 'IDENTIFIER'}
{'value': '(', 'LINE_NUMBERS': 5, 'TYPE': 'LL_BRACKET'}
{'value': 'n', 'LINE_NUMBERS': 5, 'TYPE': 'IDENTIFIER'}
{'value': ')', 'LINE_NUMBERS': 5, 'TYPE': 'RL_BRACKET'}
{'value': ':', 'LINE_NUMBERS': 5, 'TYPE': 'COLON'}
{'value': 'print', 'LINE_NUMBERS': 6, 'TYPE': 'IDENTIFIER'}
{'value': '(', 'LINE_NUMBERS': 6, 'TYPE': 'LL_BRACKET'}
{'value': 'n', 'LINE_NUMBERS': 6, 'TYPE': 'IDENTIFIER'}
{'value': ')', 'LINE_NUMBERS': 6, 'TYPE': 'RL_BRACKET'}
{'value': '$', 'LINE_NUMBERS': 7, 'TYPE': 'EOF'}
ERROR IN START

You have other options like passing the file path in the arguments or reading from a file location, but this would require some modification as the original program is not readily consumable.

For example:

with open("my/file.py", "r") as f:
    blank_var = f.read()

CodePudding user response:

So I actually figured out how to get another file to run.

For anyone having the same problem as me, here's the code I used:

    file = open("happy.py")
    blank_var= file.read()
    print("INPUT FILE:\n", blank_var)

!!!

  • Related