programing

IDLE 대화형 셸에서 파이썬 스크립트를 실행하는 방법은 무엇입니까?

telebox 2023. 7. 31. 21:20
반응형

IDLE 대화형 셸에서 파이썬 스크립트를 실행하는 방법은 무엇입니까?

IDLE 대화형 셸 내에서 파이썬 스크립트를 실행하려면 어떻게 해야 합니까?

다음은 오류를 발생시킵니다.

>>> python helloworld.py
SyntaxError: invalid syntax

파이썬3:

exec(open('helloworld.py').read())

파일이 동일한 dir에 없는 경우:

exec(open('./app/filename.py').read())

글로벌/로컬 변수 전달에 대한 내용은 https://stackoverflow.com/a/437857/739577 을 참조하십시오.

참고: 윈도우에서 실행 중인 경우 이중 슬래시 "//"를 사용해야 합니다. 그렇지 않으면 오류가 발생합니다.


사용되지 않는 Python 버전

Python2 내장 함수: execfile

execfile('helloworld.py')

일반적으로 인수를 사용하여 호출할 수 없습니다.그러나 해결 방법은 다음과 같습니다.

import sys
sys.argv = ['helloworld.py', 'arg']  # argv[0] should still be the script name
execfile('helloworld.py')

2.6 이후 사용되지 않음: popen

import os
os.popen('python helloworld.py') # Just run the program
os.popen('python helloworld.py').read() # Also gets you the stdout

인수 포함:

os.popen('python helloworld.py arg').read()

사전사용 : 하위공정

import subprocess
subprocess.call(['python', 'helloworld.py']) # Just run the program
subprocess.check_output(['python', 'helloworld.py']) # Also gets you the stdout

인수 포함:

subprocess.call(['python', 'helloworld.py', 'arg'])

자세한 내용은 문서를 읽어보세요 :-)


이 기본 사항으로 테스트됨helloworld.py:

import sys
if len(sys.argv) > 1:
    print(sys.argv[1])

이것은 python3에서 사용할 수 있습니다.

exec(open(filename).read())

IDLE 셸 창이 터미널 셸과 동일하지 않습니다(예: 실행 중).sh또는bash) 오히려 파이썬 인터렉티브 인터프리터에 있는 것과 같습니다(python -i) IDLE에서 스크립트를 실행하는 가장 쉬운 방법은Open로부터의 명령File메뉴(실행 중인 플랫폼에 따라 약간 다를 수 있음)를 사용하여 스크립트 파일을 IDLE 편집기 창에 로드한 다음Run->Run Module명령(바로 가기 F5).

가장 쉬운 방법

python -i helloworld.py  #Python 2

python3 -i helloworld.py #Python 3

사용해 보세요.

import os
import subprocess

DIR = os.path.join('C:\\', 'Users', 'Sergey', 'Desktop', 'helloword.py')

subprocess.call(['python', DIR])

execFile('helloworld.py')나를 위해 일을 합니다.Python 폴더 자체에 없는 경우 .py 파일의 전체 디렉터리 이름을 입력해야 합니다(최소한 Windows의 경우는 이와 같습니다).

예를들면,execFile('C:/helloworld.py')

파이썬 콘솔에서 다음과 같은 두 가지 방법을 시도할 수 있습니다.

동일한 작업 디렉토리 아래에서,

>> 헬로 월드 가져오기

변수 x가 있으면 IDLE에 출력할 수 있습니다.

>> 안녕하세요 world.x.

만약 당신이 함수 함수가 있다면, 당신은 그것을 이렇게 부를 수도 있습니다.

>> 안녕하세요.func()

>> runfile("./helloworld.py ")

예:

import subprocess

subprocess.call("C:\helloworld.py")

subprocess.call(["python", "-h"])

Python 3에는 다음이 없습니다.execFile다음과 같은 내장 기능을 사용할 수 있습니다.

import helloworld
exec('helloworld')

IDLE에서는 다음이 작동합니다.

import helloworld

왜 효과가 있는지는 잘 모르겠지만, 효과가 있습니다.

Idle과 같은 파이썬 셸이나 장고 셸에서 파이썬 스크립트를 실행하려면 exec() 함수를 사용하여 다음을 수행할 수 있습니다.Exec()이 코드 개체 인수를 실행합니다.Python의 코드 개체는 단순히 컴파일된 Python 코드입니다.따라서 스크립트 파일을 먼저 컴파일한 다음 exec()을 사용하여 실행해야 합니다.당신의 껍데기로부터:

>>>file_to_compile = open('/path/to/your/file.py').read()
>>>code_object = compile(file_to_compile, '<string>', 'exec')
>>>exec(code_object)

파이썬 3.4를 사용하고 있습니다.자세한 내용은 컴파일실행 문서를 참조하십시오.

제가 이것을 테스트해봤는데 잘 해결되었습니다.

exec(open('filename').read())  # Don't forget to put the filename between ' '

당신은 두 가지 방법으로 그것을 할 수 있습니다.

  • import file_name

  • exec(open('file_name').read())

그러나 프로그램이 실행되는 곳에 파일을 저장해야 합니다.

윈도우즈 환경에서는 다음 구문을 사용하여 Python3 셸 명령줄에서 py 파일을 실행할 수 있습니다.

exec("file_name'의 절대 경로를 엽니다. read")

아래는 python 셸 명령줄에서 간단한 helloworld.py 파일을 실행하는 방법을 설명합니다.

파일 위치: C:/Users/testuser/testfolder/helloworld.py

파일 내용: 인쇄("hello world")

다음과 같이 Python 3.7 Shell에서 이 파일을 실행할 수 있습니다.

>>> import os
>>> abs_path = 'C://Users/testuser/testfolder'
>>> os.chdir(abs_path)
>>> os.getcwd()
'C:\\Users\\testuser\\testfolder'

>>> exec(open("helloworld.py").read())
hello world

>>> exec(open("C:\\Users\\testuser\\testfolder\\helloworld.py").read())
hello world

>>> os.path.abspath("helloworld.py")
'C:\\Users\\testuser\\testfolder\\helloworld.py'
>>> import helloworld
hello world

(창문에 대한) 대안이 하나 더 있습니다.

    import os
    os.system('py "<path of program with extension>"')

언급URL : https://stackoverflow.com/questions/17247471/how-to-run-a-python-script-from-idle-interactive-shell

반응형