开发者

How to run Python file in another python file?

开发者 https://www.devze.com 2022-12-07 21:38 出处:网络
I\'m trying to 开发者_运维技巧run another python file within this lexical analyzer, but it\'s not working. Can anyone help me?

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 :)


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()
0

精彩评论

暂无评论...
验证码 换一张
取 消