我正在尝试通过在Windows上的运行对话框中键入文件名来直接运行我的Python脚本,但我无法有效地执行此操作。我在阅读Python上的Automate书之后创建了两个简单的脚本:一个是应该接受命令行参数的剪贴板,另一个是应该生成文本文件的脚本。我修改了环境变量以适应这些文件的路径,甚至为它们添加了一个shebang行。我还尝试为每个文件创建一个批处理文件。然而,当我尝试运行它们中的任何一个时,特别是使用运行对话框而不是.pyw文件的文本生成脚本时,它会非常简短地显示命令提示符,但实际上并不生成文件。当我双击它,从命令行或从Python shell运行它时,脚本运行得很好。我该如何解决这个问题?
这是文本生成脚本的代码,如果它可以使用:
#! /usr/bin/python
import random
# The quiz data. Keys are states and values are their capitals.
capitals = {'Alabama': 'Montgomery', 'Alaska': 'Juneau', 'Arizona': 'Phoenix',
'Arkansas': 'Little Rock', 'California': 'Sacramento', 'Colorado': 'Denver',
'Connecticut': 'Hartford', 'Delaware': 'Dover', 'Florida': 'Tallahassee',
'Georgia': 'Atlanta', 'Hawaii': 'Honolulu', 'Idaho': 'Boise', 'Illinois':
'Springfield', 'Indiana': 'Indianapolis', 'Iowa': 'Des Moines', 'Kansas':
'Topeka', 'Kentucky': 'Frankfort', 'Louisiana': 'Baton Rouge', 'Maine':
'Augusta', 'Maryland': 'Annapolis', 'Massachusetts': 'Boston', 'Michigan':
'Lansing', 'Minnesota': 'Saint Paul', 'Mississippi': 'Jackson', 'Missouri':
'Jefferson City', 'Montana': 'Helena', 'Nebraska': 'Lincoln', 'Nevada':
'Carson City', 'New Hampshire': 'Concord', 'New Jersey': 'Trenton',
'New Mexico': 'Santa Fe', 'New York': 'Albany', 'North Carolina': 'Raleigh',
'North Dakota': 'Bismarck', 'Ohio': 'Columbus', 'Oklahoma': 'Oklahoma City',
'Oregon': 'Salem', 'Pennsylvania': 'Harrisburg', 'Rhode Island': 'Providence',
'South Carolina': 'Columbia', 'South Dakota': 'Pierre', 'Tennessee':
'Nashville', 'Texas': 'Austin', 'Utah': 'Salt Lake City', 'Vermont':
'Montpelier', 'Virginia': 'Richmond', 'Washington': 'Olympia',
'West Virginia': 'Charleston', 'Wisconsin': 'Madison', 'Wyoming': 'Cheyenne'}
for quiz_num in range(35):
quiz_file = open('quiz_questions %s.txt' % (quiz_num+1), 'w')
quiz_answers = open('quiz_answers %s.txt' % (quiz_num+1), 'w')
quiz_file.write('Name:\nMatric no:\nDate: \n \n')
quiz_file.write(' '*40 + "Ajanlekoko Nursery and Primary School \n \n")
states = list(capitals.keys())
random.shuffle(states)
for qst_num in range (50):
right_answer = capitals[states[qst_num]]
wrong_answers = list(capitals.values())
del wrong_answers[wrong_answers.index(right_answer)]
wrong_answers = random.sample(wrong_answers, 3)
options = wrong_answers + [right_answer]
random.shuffle(options)
quiz_file.write('%s. What is the capital of %s?' % (qst_num+1, states[qst_num]))
for i in range(4):
quiz_file.write('\n \n %s. %s \n' % ('ABCD'[i], options[i]) )
quiz_file.write('\n')
quiz_answers.write('%s. %s \n' % (qst_num+1, 'ABCD'[options.index(right_answer)]) )
quiz_file.close()
quiz_answers.close()
答案 0 :(得分:0)
经过一番挖掘后,我发现这是我问题最简单的答案:
import random
import os
import sys
os.chdir(os.path.dirname(sys.argv[0]))
这会在运行脚本时将工作目录更改为第一个命令行参数(脚本的名称)。